【问题标题】:Sort a list of lists based on an internal list variable in R根据 R 中的内部列表变量对列表列表进行排序
【发布时间】:2019-04-15 08:47:55
【问题描述】:

我使用 R 中的向量创建了一个列表列表(比如说parentList)。parentList 由 100 个列表 childList1childList2 等组成。每个这样的childList 都包含一个元素列表(grandChildVariable1grandChildVariable2 等等)。除parentList 外,所有列表和变量均未命名。

我想根据每个 childList 的第二个元素 (grandChildVariable2) 对 parentList 进行排序。我可以使用parentList[[2]][2] 获取此变量的值。但我不太确定如何对整个列表进行排序。

我目前正在尝试按如下方式对其进行排序: sorted_list <- parentList[order(sapply(parentList,'[[',2))] 但它只拾取第二个列表元素 childList2 并返回以下错误:unimplemented type 'list' in 'orderVector1'

【问题讨论】:

    标签: r list sorting vector


    【解决方案1】:

    我认为这应该可行。先提取值然后使用它们对父列表进行排序会更容易一些。

    childList1 <- list(grandChildVariable1 = 1,
                   grandChildVariable2 = 10)
    childList2 <- list(grandChildVariable1 = 1,
                   grandChildVariable2 = 30)
    childList3 <- list(grandChildVariable1 = 1,
                   grandChildVariable2 = 20)
    parentList <- list(childList1, childList2,childList3)
    
    x <- sapply(parentList, function(x) x[[2]])
    
    orderedParentList <- parentList[order(x)]
    str(orderedParentList)
    

    【讨论】:

    • 这可能有点整洁:x
    • 而不是循环
    • 编辑您的答案以使其更易于访问。我也觉得挺好的。
    【解决方案2】:

    我能够找出unimplemented type 'list' in 'orderVector1' 问题的根本原因。原因是某些childList 元素为NULL。当我验证 parentList 不包含 NULL 时,我能够正确完成排序。

    使用sorted_list &lt;- parentList[order(sapply(parentList,'[[',2))] 给出了预期的正确输出,Cleland 给出的答案也可以解决问题。

    【讨论】:

      猜你喜欢
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2021-05-02
      • 2015-01-08
      • 2023-03-19
      相关资源
      最近更新 更多