111

See below:

paste("perf.a", "1", sep="")
# [1] "perf.a1"

What if I want to assign a value to perf.a1?

I tried as.name, as.symbol, etc., with no avail:

as.name(paste("perf.a", "1", sep="")) = 5
# Error in as.name(paste("perf.a", "1", sep = "")) = 5 : 
#   target of assignment expands to non-language object
as.symbol(paste("perf.a", "1", sep="")) = 5
# Error in as.symbol(paste("perf.a", "1", sep = "")) = 5 : 
#   target of assignment expands to non-language object
noquote(paste("perf.a", "1", sep="")) = 5
# Error in noquote(paste("perf.a", "1", sep = "")) = 5 : 
#   target of assignment expands to non-language object
gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79
qed
  • 22,298
  • 21
  • 125
  • 196
  • 3
    Duplicate? http://stackoverflow.com/questions/2679193/how-to-name-variables-on-the-fly-in-r – Marek Apr 01 '11 at 11:10
  • 2
    And some others: http://stackoverflow.com/questions/2907896/how-to-assign-to-the-names-attribute-of-the-value-of-a-variable-in-r, http://stackoverflow.com/questions/2899581/assign-subset-of-parent-table-to-objects-in-r, http://stackoverflow.com/questions/3094111/r-turning-list-items-into-objects, http://stackoverflow.com/questions/2590043/creating-a-series-of-vectors-from-a-vector – Marek Apr 01 '11 at 11:13
  • it seems like this post is the oldest one, the other were duplicate (lol – S.F. Yeh Jun 07 '22 at 01:24

4 Answers4

158

You can use assign (doc) to change the value of perf.a1:

> assign(paste("perf.a", "1", sep=""),5)
> perf.a1
[1] 5
lecodesportif
  • 10,737
  • 9
  • 38
  • 58
19

See ?assign.

> assign(paste("tra.", 1, sep = ""), 5)
> tra.1
  [1] 5
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
13

In my case function eval() works very good. Below I generate 10 variables and assign them 10 values.

lhs <- rnorm(10)
rhs <- paste("perf.a", 1:10, "<-", lhs, sep="")
eval(parse(text=rhs))
Michael Romanov
  • 141
  • 1
  • 2
  • Not usable if the RHS is complicated or big. Moreover, even in simple cases, there is some precision loss: `a <- rnorm(1); a - eval(parse(text=paste(a)))` does not return `0` usually. –  Oct 07 '19 at 13:31
3

In my case the symbols I create (Tax1, Tax2, etc.) already had values but I wanted to use a loop and assign the symbols to another variable. So the above two answers gave me a way to accomplish this. This may be helpful in answering your question as the assignment of a value can take place anytime later.

output=NULL
for(i in 1:8){
   Tax=eval(as.symbol(paste("Tax",i,sep="")))
   L_Data1=L_Data_all[which(L_Data_all$Taxon==Tax[1] | L_Data_all$Taxon==Tax[2] | L_Data_all$Taxon==Tax[3] | L_Data_all$Taxon==Tax[4] | L_Data_all$Taxon==Tax[5]),]
   L_Data=L_Data1$Length[which(L_Data1$Station==Plant[1] | L_Data1$Station==Plant[2])]
   h=hist(L_Data,breaks=breaks,plot=FALSE)
   output=cbind(output,h$counts)
}