how to assign to the names() attribute of the value of a variable in R

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-29 05:11:29

In the form you ask question there is no need to assign names. If you x exists then you do names(x) <- v. This is right way to do this.

If your variable name is unknown (i.e. dynamically created) then you could use substitute

nm <- "xxx" # name of your variable
v <- 1:3 # value
assign(nm,v) # assign value to variable

w <- c("a","b","c") # names of variable
eval(substitute(names(x)<-w, list(x=as.symbol(nm))))
# Result is
str(xxx)
# Named int [1:3] 1 2 3
# - attr(*, "names")= chr [1:3] "a" "b" "c"

But if you must do this kind of tricks there is something wrong with you code.

Try this:

assign(paste(names(x),collapse="."), v)

Use collapse instead if there are multiple names.

> v <- 1:10
> names(v) <- letters[1:10]
> v
 a  b  c  d  e  f  g  h  i  j 
 1  2  3  4  5  6  7  8  9 10 
> assign(paste(names(v), collapse=""), v)
> abcdefghij
 a  b  c  d  e  f  g  h  i  j 
 1  2  3  4  5  6  7  8  9 10

Marek's answer works, but Aniko's question is a simple answer.

nm <- "xxx"; v<- 1:3; names(v) <- c("a","b","c"); assign(nm,v)

This is Aniko's answer, she should get credit.

The case I use this for has >1 classes of queries, each with a different varname, and each class containing >1 sql query. So, say, a query class name of "config_query" with three named queries in a list, say "q1", "q2", "q3". And further query class names. I want to make a loop that will take the root prefixes (such as "config" for "config_query") of query class names as a list, get their query contents, run the queries, and list the result data frames in result class varnames such as "config_result", such that each result in "config_result" has the same name as the query in "config_query" which it's the result of.

Said differently, I want result class varnames and corresponding name mappings for free, given root prefixes and initial queries. Using assign() assigns to result class varnames. I was stuck on how to do the name mappings. Thanks!

user3712671

If the name of the variable is stored as a string in other variable (variable_name), I will do the following.

temp <- get(variable_name)

names(temp)<- array_of_names

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