I have a data frame in which each ID belongs to a unique group. I wish to create a summarize table which tells me the number of observations for each id and which group it belongs to.
dat=data.frame(id=c(1,1,1,2,2,2,2,3,4,4,4,4,4),group=c(1,1,1,0,0,0,0,1,0,0,0,0,0))
count=dat%>% group_by(id)%>% tally()
## A tibble: 4 x 2
id n
<dbl> <int>
1 1 3
2 2 4
3 3 1
4 4 5
with the code above I can count the number of observations. But I have no idea how to create a third column for group. The desired result is:
# A tibble: 4 x 3
id n group
<dbl> <int> <dbl>
1 1 3 1
2 2 4 0
3 3 1 1
4 4 5 0
When I do
dat %>% group_by(id) %>% summarise(n=count(id), group = unique(group))
I go a error: Error in quickdf(.data[names(cols)]) : length(rows) == 1 is not TRUE However, when I do
dat %>% group_by(id) %>% summarise( group = unique(group))
It worked. I was so confused why the summarise command can not take multiple arguments. Update: the error is caused by another package called"plyr". Summarise is working well when I detached plyr.