在 R 中用“粘贴”创建一个变量名?

见下文:

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

如果我想给 perf.a1赋一个值怎么办?

我试了 as.nameas.symbol等等,都没有用:

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
139856 次浏览

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

> assign(paste("perf.a", "1", sep=""),5)
> perf.a1
[1] 5

See ?assign.

> assign(paste("tra.", 1, sep = ""), 5)
> tra.1
[1] 5

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))

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)
}