如何使用for循环创建一系列列表元素

时间:2019-08-24 14:39:59

标签: r list loops

我是一个新手,所以如果在此之前已经问过我可以肯定的话,请事先道歉,但是在四处搜寻之后我仍然很茫然。高级:我有一些包含多个时间序列的大型数据框,试图在其中创建各个时间序列的列表。数据的标识符结构不佳,因此沿分割路线走下去似乎并不对劲,为什么我要尝试子设置路线。

问题可以这样显示:

set.seed(1)
test1<-matrix(rnorm(90), nrow = 10, ncol = 9)
testobj<-list()
indexlist<- list(1:3, 4:6, 7:9)

for( i in indexlist){
    for( j in (1:3)) {
        testobj[[j]]<-test1[,i]
    }
}

结果是我的列表testobj是包含test1[,7:9]而不是

的最后一个子集元素的3个元素的列表
testobj[[1]]<-test1[,1:3]
testobj[[2]]<-test1[,4:6]
testobj[[3]]<-test1[,7:9]

我真的很想。当我在控制台中运行for(i in indexlist){print(i)}时,它似乎会生成正确的3个子集索引,因此,如果有人可以帮助解释其错误原因并提出更正建议,将不胜感激。

2 个答案:

答案 0 :(得分:0)

如果要使用for循环,则只需一个循环即可遍历indexlist

for( i in seq_along(indexlist)) { 
     testobj[[i]] <- test1[,indexlist[[i]]] 
}

#[[1]]
#            [,1]        [,2]        [,3]
# [1,] -0.6264538  1.51178117  0.91897737
# [2,]  0.1836433  0.38984324  0.78213630
# [3,] -0.8356286 -0.62124058  0.07456498
# [4,]  1.5952808 -2.21469989 -1.98935170
# [5,]  0.3295078  1.12493092  0.61982575
# [6,] -0.8204684 -0.04493361 -0.05612874
# [7,]  0.4874291 -0.01619026 -0.15579551
# [8,]  0.7383247  0.94383621 -1.47075238
# [9,]  0.5757814  0.82122120 -0.47815006
#[10,] -0.3053884  0.59390132  0.41794156

#[[2]]
#             [,1]       [,2]       [,3]
# [1,]  1.35867955 -0.1645236  0.3981059
#...

但是,您也可以使用lapply

lapply(indexlist, function(x) test1[, x])

答案 1 :(得分:0)

我们可以将sapplysimplify = FALSE一起使用

sapply(indexlist, function(x) test1[, x] , simplify = FALSE)
#[[1]]
#            [,1]        [,2]        [,3]
# [1,] -0.6264538  1.51178117  0.91897737
# [2,]  0.1836433  0.38984324  0.78213630
# [3,] -0.8356286 -0.62124058  0.07456498
# [4,]  1.5952808 -2.21469989 -1.98935170
# [5,]  0.3295078  1.12493092  0.61982575
# [6,] -0.8204684 -0.04493361 -0.05612874
# [7,]  0.4874291 -0.01619026 -0.15579551
# [8,]  0.7383247  0.94383621 -1.47075238
# [9,]  0.5757814  0.82122120 -0.47815006
#[10,] -0.3053884  0.59390132  0.41794156

#[[2]]
#             [,1]       [,2]       [,3]
# [1,]  1.35867955 -0.1645236  0.3981059
# [2,] -0.10278773 -0.2533617 -0.6120264
# [3,]  0.38767161  0.6969634  0.3411197
# [4,] -0.05380504  0.5566632 -1.1293631
# [5,] -1.37705956 -0.6887557  1.4330237
# [6,] -0.41499456 -0.7074952  1.9803999
# [7,] -0.39428995  0.3645820 -0.3672215
# [8,] -0.05931340  0.7685329 -1.0441346
# [9,]  1.10002537 -0.1123462  0.5697196
#[10,]  0.76317575  0.8811077 -0.1350546

#[[3]]
#             [,1]         [,2]       [,3]
# [1,]  2.40161776  0.475509529 -0.5686687
# [2,] -0.03924000 -0.709946431 -0.1351786
# [3,]  0.68973936  0.610726353  1.1780870
# [4,]  0.02800216 -0.934097632 -1.5235668
# [5,] -0.74327321 -1.253633400  0.5939462
# [6,]  0.18879230  0.291446236  0.3329504
# [7,] -1.80495863 -0.443291873  1.0630998
# [8,]  1.46555486  0.001105352 -0.3041839
# [9,]  0.15325334  0.074341324  0.3700188
#[10,]  2.17261167 -0.589520946  0.2670988

或者使用map中的purrr

library(purrr)
map(indexlist, ~ test1[, .x])