如何有效地遍历包含不同长度向量的列表

How can I efficiently loop trough a list containing vectors of different length

我有一个包含不同长度向量的列表,我需要高效地循环这些向量。作为示例,我想在每个元素上使用打印功能。但是因为我会反复遇到这个问题,所以我想找到一个有效的方法来解决这个问题。

list <- list(1, c(1:4), c(3:10))

for (i in seq_along(list)) {
  for(j in seq_along(list[[i]])){
    print(list[[i]][j])
  }
}

感谢任何帮助。

尝试rapply,即

rapply(list, print)
#[1] 1
#[1] 1 2 3 4
#[1]  3  4  5  6  7  8  9 10
# [1]  1  1  2  3  4  3  4  5  6  7  8  9 10

因为您对效率感兴趣,所以我添加了一个基准测试示例来评估 (1) 您的方法 (2) @Sotos 提出的方法 (3) 使用 lapply 和 (4) 使用 lapply 和 sapply:

遍历列表元素(向量元素)的方法
list2examine <- list(1, c(1:4), c(3:10))

    benchmark("original"= {
  for (i in seq_along(list2examine)) {
    for(j in seq_along(list2examine[[i]])){
      print(list2examine[[i]][j])
    }
  }
}, "Sotos" = {rapply(list2examine, print)},
"lapply" = {lapply(list2examine, function(x) {print(x)} )},
"lapplySapply" = {lapply(list2examine, function(x) { sapply(x, function(i) {print(i)} ) })},
"ismirsehregal" = { print(unlist(list2examine))},

replications=1000,
columns = c("test", "replications", "elapsed",
            "relative", "user.self", "sys.self"))

           test replications elapsed relative user.self sys.self
5 ismirsehregal         1000    0.08    1.000      0.07     0.02
3        lapply         1000    0.11    1.375      0.11     0.00
4  lapplySapply         1000    0.34    4.250      0.36     0.00
1      original         1000    2.80   35.000      2.81     0.07
2         Sotos         1000    0.14    1.750      0.17     0.00

如您所见,您的方法是您预期中最慢的(“经过”)。 lapplySapply 比 rapply 慢,我猜这与 rapply 是递归函数这一事实有关。如果您想进一步阅读基准测试或如何解释函数的结果,我推荐文章 https://www.r-bloggers.com/2017/05/5-ways-to-measure-running-time-of-r-code/.

请注意,我已经更改了您列表的名称,因为变量名称不应与 r 的内置函数相同。

此外,请记住,但是,这些函数都是打印列表中的条目,它们在迭代形式上有所不同。