访问R中列表中的列表元素

时间:2018-09-22 14:36:44

标签: r list loops matrix

我有一个坐标对列表列表,这些列表是从SpatialLinesData框架sldf中提取的-列表中的每个列表代表一个单独的线串:

res <- lapply(slot(sldf, "lines"), function(x) lapply(slot(x, "Lines"), 
                                                     function(y) slot(y, "coords"))) 


> str(res)
List of 1683
 $ :List of 1
  ..$ : num [1:130, 1:2] -122 -122 -122 -122 -122 ...
 $ :List of 1
  ..$ : num [1:120, 1:2] -122 -122 -122 -122 -122 ...
 $ :List of 1
  ..$ : num [1:162, 1:2] -122 -122 -122 -122 -122 ...
 $ :List of 1
  ..$ : num [1:34, 1:2] -122 -122 -122 -122 -122 ...

我的目标是遍历每个线串的每个坐标对并打印该坐标对。

for (i in 1:length(res){

  print(res[i])

}

将这样打印每个列表:

[[1]]
[[1]][[1]]
            [,1]     [,2]
  [1,] -122.4449 37.76559
  [2,] -122.4449 37.76559
  [3,] -122.4449 37.76559
  [4,] -122.4449 37.76559 ...
列表中的

。更进一步,我能够打印每个列表的各个行号。

for (i in 1:length(res)){

  for (i in 1:length(res[i][[1]][[1]]))
  {
    print(i)
  }

}

如何一步一步获得每个坐标对?

以下内容会产生错误subscript out of bounds

for (i in 1:length(res)){

  for (i in 1:length(res[i][[1]][[1]]))
  {
    print(res[1][[1]][[1]][i,])
  }

}

1 个答案:

答案 0 :(得分:2)

考虑一下申请族中很少使用的成员rapply(递归的申请成员):

rapply(res, print)

演示:

set.seed(9222018)
# NESTED LIST OF FIVE LISTS EACH WITH ONE 5 X 2 MATRIX
res <- lapply(1:5, function(x) list(replicate(2, runif(5))))

str(res)
# List of 5
#  $ :List of 1
#   ..$ : num [1:5, 1:2] 0.233 0.959 0.242 0.131 0.924 ...
#  $ :List of 1
#   ..$ : num [1:5, 1:2] 0.0347 0.0409 0.9717 0.1854 0.6874 ...
#  $ :List of 1
#   ..$ : num [1:5, 1:2] 0.579 0.994 0.339 0.554 0.188 ...
#  $ :List of 1
#   ..$ : num [1:5, 1:2] 0.306 0.828 0.29 0.416 0.57 ...
#  $ :List of 1
#   ..$ : num [1:5, 1:2] 0.722 0.117 0.292 0.32 0.131 ...

输出

out <- rapply(res, print, how="list")

#           [,1]      [,2]
# [1,] 0.2334018 0.4563486
# [2,] 0.9593926 0.8900761
# [3,] 0.2415238 0.1898711
# [4,] 0.1312646 0.2723704
# [5,] 0.9238483 0.5405712
#            [,1]      [,2]
# [1,] 0.03469751 0.6921262
# [2,] 0.04085011 0.9977958
# [3,] 0.97173617 0.7002101
# [4,] 0.18537097 0.7687420
# [5,] 0.68738469 0.8482499
#           [,1]       [,2]
# [1,] 0.5789794 0.53362949
# [2,] 0.9938713 0.06445358
# [3,] 0.3390548 0.56161016
# [4,] 0.5536486 0.69291413
# [5,] 0.1878046 0.34357447
#           [,1]      [,2]
# [1,] 0.3062696 0.8913562
# [2,] 0.8281726 0.7861409
# [3,] 0.2902253 0.3713141
# [4,] 0.4156087 0.8301594
# [5,] 0.5695427 0.5160663
#           [,1]      [,2]
# [1,] 0.7217106 0.3459698
# [2,] 0.1174953 0.4014062
# [3,] 0.2917907 0.6519540
# [4,] 0.3204130 0.6228116
# [5,] 0.1309318 0.9475084

由于我们在不更改元素的情况下打印每个元素,因此 out res 完全相同:

identical(res, out)
# TRUE