Why can't I name vector elements inside c() with tags indexed from other variable?

一曲冷凌霜 提交于 2019-12-11 02:27:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!