scrollex
scrollex

Reputation: 2723

How can I count the number of instances a value occurs within a subgroup in R?

I have a data frame that I'm working with in R, and am trying to check how many times a value occurs within its larger, associated group. Specifically, I'm trying to count the number of cities that are listed for each particular country.

My data look something like this:

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

It seems that table() is the way to go, but I can't quite figure it out — how can I find out how many cities are listed for each country? That is to say, how can I find out how many fields in one column are associated with a particular value in another column?

EDIT:

I'm hoping for something along the lines of

3    US
2    France
1    Germany

Upvotes: 1

Views: 9587

Answers (1)

akrun
akrun

Reputation: 887881

I guess you can try table.

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

Or using data.table

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

Or

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

Upvotes: 8

Related Questions