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

Tony picture Tony · May 25, 2010 · Viewed 16.2k times · Source

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.

Answer

Marek picture Marek · May 25, 2010

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.