简体   繁体   中英

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

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.

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 (ie 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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM