Create a variable name with "paste" in R?
Solution 1
You can use assign
(doc) to change the value of perf.a1:
> assign(paste("perf.a", "1", sep=""),5)
> perf.a1
[1] 5
Solution 2
See ?assign
.
> assign(paste("tra.", 1, sep = ""), 5)
> tra.1
[1] 5
Solution 3
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))
Solution 4
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)
}
Related videos on Youtube
qed
Ph.D. in computational genomics, now working in the industry on computer vision / deep learning projects. Also lend a hand on RESTful API building at times. Use python/scala/julia/go, have great hopes for julia. 世上无难事,只怕有心人。
Updated on December 03, 2020Comments
-
qed over 3 years
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
-
Marek almost 13 yearsDuplicate? stackoverflow.com/questions/2679193/…
-
Marek almost 13 years
-
-
lamecicle over 9 yearsWhy was this so hard to find!
-
Louis Maddox almost 9 years
assign(paste0("perf.a", "1"), 5)
is a bit neater -
Admin over 4 yearsNot 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 return0
usually.