【问题标题】:How to get the frequency of items in a list with the different length如何获取列表中不同长度的项目的频率
【发布时间】:2013-03-12 02:58:56
【问题描述】:

假设我有以下列表:

test<-list(c("a","b","c"),c("a"),c("c"))
>test
[[1]]
[1] "a" "b" "c"

[[2]]
[1] "a"

[[3]]
[1] "c"

我该怎么做(或使用函数)来获取列表中唯一项目的频率,如下所示:?

a 2
b 1
c 2

我尝试使用 table(test),但出现以下错误

> table(test)
Error in table(test) : all arguments must have the same length

【问题讨论】:

    标签: r list


    【解决方案1】:
    test <- list(c("a", "b", "c"), c("a"), c("c"))
    # If you want count accross all elements
    table(unlist(test))
    ## 
    ## a b c 
    ## 2 1 2 
    
    
    # If you want seperate counts in each item of list
    lapply(test, table)
    ## [[1]]
    ## 
    ## a b c 
    ## 1 1 1 
    ## 
    ## [[2]]
    ## 
    ## a 
    ## 1 
    ## 
    ## [[3]]
    ## 
    ## c 
    ## 1 
    ## 
    

    【讨论】:

      【解决方案2】:

      首先使用unlist

      table(unlist(test))
      

      【讨论】:

        猜你喜欢
        • 2021-07-25
        • 1970-01-01
        • 2022-10-14
        • 2016-09-27
        • 1970-01-01
        • 1970-01-01
        • 2012-02-08
        • 1970-01-01
        • 2020-11-27
        相关资源
        最近更新 更多