maximusdooku
maximusdooku

Reputation: 5512

How can I aggregate unique occurrences by year?

I have a dataframe of this format

col1 col2 col3 col4
1980 4
1980 4
1980 7
1980 32
1981 3
1981 3
1981 3
1981 3
1981 9
1992 10
1992 11

And I would like to have a dataframe of this nature:

col1 col2
1980 3
1981 2
1992 2

Basically, to count the number of unique occurrences of col2 every year. The dataframe contains lots of other columns (col3,col4 etc), but not a part of this analysis. I have previously used table to summarize for a single column, but don't know how to do this.

Upvotes: 0

Views: 64

Answers (1)

Shenglin Chen
Shenglin Chen

Reputation: 4554

aggregate(col2~col1,df,function(x)length(unique(x)))

or 
library(dplyr)
df%>%group_by(col1)%>%summarize(count=length(unique(col2)))

Upvotes: 2

Related Questions