R 循环和变量名

R 循环和变量名,r,loops,R,Loops,下面是一个小例子: temp<-0 a1<-1 a2<-2 a3<-3 a4<-4 for(i in 1:4) { temp<-temp+a* # temp+a1|a2|a3|a4 ... } temp可以将这些值放在一个向量中: temp<-0 a<-c(1,2,3,4) #or 1:4 for(i in 1:4) { temp<-temp+a[i] # temp+a1|a2|a3|a4 ... } %%++

下面是一个小例子:

temp<-0
a1<-1
a2<-2
a3<-3
a4<-4

for(i in 1:4) {
  temp<-temp+a*     # temp+a1|a2|a3|a4 ...
}

temp可以将这些值放在一个向量中:

temp<-0
a<-c(1,2,3,4) #or 1:4

for(i in 1:4) {
  temp<-temp+a[i]     # temp+a1|a2|a3|a4 ...
}
%%++
是用于从
stringi
包进行字符串连接的运算符。 要安装此软件,请运行:

install.packages("stringi")
require(stringi)

您可以使用
paste0
来定义名称和索引,而不仅仅是使用
get
通过字符串名称引用变量

for(i in 1:4) {
    temp <- temp + get(paste0("a", i))
}
for(1:4中的i){

temp请指定您试图实现的目标,目前还不清楚。为什么不使用
a我添加了一个新的示例。您的环境中不应该有50-150个不同对象中的50-150个矩阵。您应该学会使用列表。然后,它就像在列表索引上循环一样简单,或者使用
lappy
Reduce之类的函数
install.packages("stringi")
require(stringi)
for(i in 1:4) {
    temp <- temp + get(paste0("a", i))
}