问题
When I name the elements of a vector I use tag - value pairs like these:
myvec <- c("name1" = 1, "name2" = 2, "name3" = 3)
> myvec
name1 name2 name3
1 2 3
When I create a vector containing the names and index this vector from inside the c()-function, it doesn't work.
namevec <- c("name1", "name2", "name3")
myvec <- c(namevec[1] = 1, namevec[2] = 2, namevec[3] = 3)
Error: unexpected '=' in "myvec <- c(namevec[1] ="
My Question now: Why is that? Why does it work if I write "name1"
, but if I use namevec[1]
, which returns "name1"
, it throws an error?
Note: I am not asking for a workaround.There are plenty, such as:
"names<-"(c(1,2,3), namevec)
name1 name2 name3
1 2 3
setNames(c(1,2,3), namevec)
name1 name2 name3
1 2 3
structure(c(1,2,3), .Names = namevec)
name1 name2 name3
1 2 3
and some more.
I was inspired by this question from a few days ago:
Naming element in rbind/list by referencing element from a character vector in R
来源:https://stackoverflow.com/questions/54762963/why-cant-i-name-vector-elements-inside-c-with-tags-indexed-from-other-variabl