'Calling list element in R's c() function
I am rather embarrassed to ask this basic question but I am having trouble calling a list element in the c().
My target output looks like this:
FO01-98KF QY85-65GA VO03-93EF
"blue" "green" "red"
Since the "title" characters keep changing depending on my input (this is happening inside a function), I want to make the assignment as general as possible.
SeqColor <- c("QY85-65GA","VO03-93EF","FO01-98KF") %>% sort()
ColorSeq <- c(SeqSort[1] = "blue", SeqSort[2] = "green", SeqSort[3] = "red")
However, I can't seem to assign the "title" by calling a vector element (the other way around is no problem). This is the warning message I get:
Error: unexpected '=' in "c(SeqSort[1] ="
Sorry for this really basic problem, but if anyone has an idea how I could get to my desired output without calling the elements in SeqColor by their name, I'd really appreciate your input.
Solution 1:[1]
You can use setNames:
setNames(ColorSeq, SeqColor)
#FO01-98KF QY85-65GA VO03-93EF
# "blue" "green" "red"
Solution 2:[2]
You need to do this as two steps, setting the values then the names:
ColorSeq <- c("blue", "green", "red")
names(ColorSeq) <- SeqColor
Solution 3:[3]
You can assign the sorted names to the colors. You can use the following code:
ColorSeq <- c("blue", "green", "red")
SeqSort <- c("QY85-65GA","VO03-93EF","FO01-98KF") %>% sort()
names(ColorSeq) <- SeqSort
ColorSeq
Output:
FO01-98KF QY85-65GA VO03-93EF
"blue" "green" "red"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maël |
| Solution 2 | Miff |
| Solution 3 | Quinten |
