r - 在 R 中从循环或 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

最佳答案

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

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]])
}

https://stackoverflow.com/questions/10389164/

相关文章:

r - 在每行中查找最小正值(不包括 0)

php - 从 php 中的文件夹中读取文件并列出 json 文件中的条目

perl - 在 Perl 中复制二维数组

unix - 在 Solaris 上如何找到谁或哪个进程向我的进程发送了信号

powershell - 使用 Powershell 为 Word 文档添加页眉和页脚

php - 是否可以使用 PHP 添加事件监听器?

maven - 你如何使用 Maven 设置 jetty-start?

ms-access - 左外加入 Access ?

php - 这个 PHP 有什么问题?什么都没有出现

wpf - 从模板绑定(bind)到 View 模型的属性