如何计算值在 R 中的子组中出现的实例数?

scr*_*lex 1 r

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

我的数据看起来像这样:

City              Country
=========================
New York           US
San Francisco      US
Los Angeles        US
Paris             France
Nantes            France
Berlin            Germany
Run Code Online (Sandbox Code Playgroud)

似乎 table() 是要走的路,但我不太明白——我怎么能找出每个国家有多少个城市?也就是说,如何找出一列中有多少字段与另一列中的特定值相关联?

编辑:

我希望有类似的东西

3    US
2    France
1    Germany
Run Code Online (Sandbox Code Playgroud)

akr*_*run 7

我想你可以试试table

table(df$Country)
# France Germany      US 
#     2       1       3 
Run Code Online (Sandbox Code Playgroud)

或使用 data.table

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

或者

library(plyr)
count(df$Country)
#        x freq
#1  France    2
#2 Germany    1
#3      US    3
Run Code Online (Sandbox Code Playgroud)