【问题标题】:Call list by name from loop or lapply, in R在 R 中按名称从循环或 lapply 调用列表
【发布时间】:2012-05-10 11:25:44
【问题描述】:

我正在尝试使用 '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

【问题讨论】:

    标签: r list call lapply


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的快速回复!完美
    • @user1034797 -- 如果 Joshua 的回答正是您所需要的,请不要忘记单击左侧的复选标记来“接受”它。谢谢。
    • 另一种可能是for (i in names(a)) {...
    • @Marek:我什至没有想到这一点。我想我在想这个列表会比 OP 想要循环的元素更多。
    【解决方案2】:

    如果您只是在列表的元素上循环以对每个元素执行某些操作(我意识到您的示例已简化),那么请考虑执行此操作的 apply 系列函数:

    lapply(a, print)
    

    以交互方式输入的内容会打印两次,因为它们会打印在 lapply 内,然后会打印 lapply 的返回值。

    【讨论】:

      【解决方案3】:

      你可以在没有索引的情况下遍历列表:

      for (ai in a) {
          print(ai)
      }
      

      这很好,除非您需要元素的名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-12
        • 1970-01-01
        • 2020-10-16
        • 2017-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多