在 R 中按名称从循环或 lapply 调用列表

mma*_*123 2 r list call lapply

我正在尝试使用“by”调用的输出,它很容易转换为列表......但有时列表仍然无视我

a = list('1'=c(19,3,4,5), '4'=c(3,5,3,2,1,6), '8'=c(1,3))

 for (i in c(1,8,4)){
    # would like to do something like this
     a[["i"]]      # calling list elements by name rather than # 
     }


 #ideally the output would be something like this

>19,3,4,5 
>1,3
>3,5,3,2,1,6
Run Code Online (Sandbox Code Playgroud)

Jos*_*ich 5

列表名称必须是字符串;它们不能是数字。您需要转换i为字符串。您可以使用as.characterorpaste并且您可以在循环开始时或在循环内部执行此操作。

a = list('1'=c(19,3,4,5), '4'=c(3,5,3,2,1,6), '8'=c(1,3))

# convert inside loop
for (i in c(1,8,4)) {
  print(a[[as.character(i)]])
}
# convert at initiation
for (i in as.character(c(1,8,4))) {
  print(a[[i]])
}
Run Code Online (Sandbox Code Playgroud)

  • 另一种可能是`for (i in names(a)) {...` (4认同)