R 如何在多个对象上循环

R 如何在多个对象上循环,r,R,最近,我经常遇到类似的问题。为了使复制变得非常容易,下面是一个非常基本的示例的一些示例数据: # create five random matrices with the same dimensions for (i in 1:5) { assign(paste0("mat", i), matrix(rexp(200), 10,10)) } # create five empty vectors with the same length for (i in 1:5) {

最近,我经常遇到类似的问题。为了使复制变得非常容易,下面是一个非常基本的示例的一些示例数据:

# create five random matrices with the same dimensions
for (i in 1:5) {
  assign(paste0("mat", i), matrix(rexp(200), 10,10))
}

# create five empty vectors with the same length
for (i in 1:5) {
  assign(paste0("vec", i), vector(mode= "numeric", length= 10))
}

# fill vec1 with the colsums of mat1
for (i in 1:10) {
  vec1[i] <- colSums(mat1)[i]
}

# fill each vector with the colsums of each corresponding matrix -> this FAILS
for (i in 1:5) {
  for (j in 1:10) {
    get(paste0("vec", i))[j] <- colSums(get(paste0("mat", i)))[j]
  }
}
#创建五个维度相同的随机矩阵
(我在1:5中){
分配(粘贴0(“材料”,i),矩阵(rexp(200),10,10))
}
#创建五个长度相同的空向量
(我在1:5中){
赋值(粘贴0(“向量”,i),向量(mode=“numeric”,length=10))
}
#用mat1的列和填充vec1
因为(我在1:10){
vec1[i]这失败了
(我在1:5中){
对于(1:10中的j){

get(paste0(“vec”,i))[j]在获取列表中的所有矩阵后,我们可以使用
lappy
,并获取
colSums

result <- lapply(mget(paste0('mat', 1:5)), colSums)
result

#$mat1
# [1]  4.40  8.07  5.78  8.72  5.82  8.47 11.06  6.41  9.85 14.91

#$mat2
# [1]  8.37 10.69 10.55  8.72 15.85  6.01 10.51  8.82 17.36  7.04

#$mat3
# [1] 13.64  6.71 11.60 13.82 10.78  6.49 10.41  6.05  3.93 10.57

#$mat4
# [1]  8.01 10.85  8.96 11.57  7.90 10.33  5.64  9.98  7.84  5.91

#$mat5
# [1] 15.03  6.55 10.54  6.14 12.57 11.70  9.55 11.05  9.36  6.89

在获得列表中的所有矩阵后,我们可以使用
lappy
,并获得
colSums

result <- lapply(mget(paste0('mat', 1:5)), colSums)
result

#$mat1
# [1]  4.40  8.07  5.78  8.72  5.82  8.47 11.06  6.41  9.85 14.91

#$mat2
# [1]  8.37 10.69 10.55  8.72 15.85  6.01 10.51  8.82 17.36  7.04

#$mat3
# [1] 13.64  6.71 11.60 13.82 10.78  6.49 10.41  6.05  3.93 10.57

#$mat4
# [1]  8.01 10.85  8.96 11.57  7.90 10.33  5.64  9.98  7.84  5.91

#$mat5
# [1] 15.03  6.55 10.54  6.14 12.57 11.70  9.55 11.05  9.36  6.89

非常感谢!这是我正在寻找的简单而智能的解决方案!非常感谢!这是我正在寻找的简单而智能的解决方案!