how to assign to the names() attribute of the valu

2019-01-24 21:54发布

问题:

In R, "assign('x',v)" sets the object whose name is 'x' to v. Replace 'x' by the result of applying a text function to a variable x. Then "assign" shows its worth.

Unfortunately, "assign(paste('names(','x',')',sep=''),v)" fails. So if 'x' is a variable x, I can set its value, but I can't give it names for its elements.

Can one work around this? a parse-eval trick maybe? Thanks.

回答1:

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.



回答2:

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


回答3:

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!



回答4:

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)