【问题标题】:R convert list that has elements of varying size to a dataframe and count distinct/unique rowsR将具有不同大小元素的列表转换为数据框并计算不同/唯一的行
【发布时间】:2015-08-20 14:20:16
【问题描述】:

如何将下面的列表转换为 data.frame?在按升序对每个元素进行排序后,我想计算该列表中的唯一元素。我打算将列表转换为 data.frame,对每一行进行排序,然后应用 distinct()。

在这种情况下,我希望答案为 3,因为当我按升序对它们进行排序时,每个元素 3 和 4 都是相同的

我更喜欢基础 R 中的函数。

abcd=list()
abcd[[1]]=c(1,2)
abcd[[3]]=c(1,2,3)
abcd[[4]]=c(3,2,1)
> abcd

> as.data.frame(abcd)
Error in data.frame(c(1, 2), NULL, c(1, 2, 3), check.names = TRUE, stringsAsFactors = TRUE) : 
  arguments imply differing number of rows: 2, 0, 3
> as.matrix(abcd)
     [,1]     
[1,] Numeric,2
[2,] NULL     
[3,] Numeric,3

【问题讨论】:

  • 你想要的输出是什么?
  • 我想计算该列表中的唯一元素。
  • 我还是不太明白你想要什么。也许只是length(unique(abcd))
  • @AnandaMahto 很抱歉造成混淆。我已经澄清了我的问题
  • @Jota,在这里使用pastecollapse 不是一个好主意,因为您可能需要小心一些极端情况。此外,没有必要进行所有这些粘贴和取消列出。

标签: r list


【解决方案1】:

你可以使用length + unique + sort,像这样:

length(unique(lapply(abcd, sort)))
# [1] 3
# Warning message:
# In is.na(x) : is.na() applied to non-(list or vector) of type 'NULL'

warning 是因为 NULL 元素。可以用suppressWarnings抑制它:

suppressWarnings(length(unique(lapply(abcd, sort))))
# [1] 3

【讨论】:

    【解决方案2】:
    > abcd=list()
    > abcd[[1]]=c(1,2)
    > abcd[[3]]=c(1,2,3)
    > unique(data.frame(unlist(abcd)))
      unlist.abcd.
    1            1
    2            2
    5            3
    

    【讨论】:

      【解决方案3】:
      table(unlist(abcd))
      
      1 2 3 
      2 2 1 
      

      或者如果你想要一个数据框

      data.frame(table(unlist(abcd)))
      
        Var1 Freq
      1    1    2
      2    2    2
      3    3    1
      

      【讨论】:

        猜你喜欢
        • 2018-08-07
        • 2023-03-22
        • 1970-01-01
        • 2015-03-11
        • 2017-01-07
        • 1970-01-01
        • 2020-07-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多