【问题标题】:How can I count the number of instances a value occurs within a subgroup in R?如何计算值在 R 的子组中出现的实例数?
【发布时间】:2014-12-15 12:23:10
【问题描述】:

我有一个在 R 中使用的数据框,并且正在尝试检查一个值在其较大的关联组中出现的次数。具体来说,我正在尝试计算每个特定国家/地区列出的城市数量。

我的数据如下所示:

City              Country
=========================
New York           US
San Francisco      US
Los Angeles        US
Paris             France
Nantes            France
Berlin            Germany

似乎 table() 是要走的路,但我不太清楚 - 我怎样才能知道每个国家/地区列出了多少个城市?也就是说,我怎样才能知道一列中有多少字段与另一列中的特定值相关联?

编辑:

我希望有类似的东西

3    US
2    France
1    Germany

【问题讨论】:

    标签: r


    【解决方案1】:

    我想你可以试试table

    table(df$Country)
    # France Germany      US 
    #     2       1       3 
    

    或使用data.table

    library(data.table)
    setDT(df)[, .N, by=Country]
    #  Country N
    #1:      US 3
    #2:  France 2
    #3: Germany 1
    

    或者

    library(plyr)
    count(df$Country)
    #        x freq
    #1  France    2
    #2 Germany    1
    #3      US    3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 2017-03-19
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      相关资源
      最近更新 更多