R: frequency with group by ID [duplicate]

爷,独闯天下 提交于 2019-12-01 07:44:26

问题


I have a data frame like this:

ID Cont
1   a
1   a
1   b
2   a
2   c
2   d

I need to report the frequence of "Cont" by ID. The output should be

ID Cont Freq
1   a    2
1   b    1
2   a    1
2   c    1
2   d    1

回答1:


Using dplyr, you can group_by both ID and Cont and summarise using n() to get Freq:

library(dplyr)
res <- df %>% group_by(ID,Cont) %>% summarise(Freq=n())
##Source: local data frame [5 x 3]
##Groups: ID [?]
##
##     ID   Cont  Freq
##  <int> <fctr> <int>
##1     1      a     2
##2     1      b     1
##3     2      a     1
##4     2      c     1
##5     2      d     1

Data:

df <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L), Cont = structure(c(1L, 
1L, 2L, 1L, 3L, 4L), .Label = c("a", "b", "c", "d"), class = "factor")), .Names = c("ID", 
"Cont"), class = "data.frame", row.names = c(NA, -6L))
##  ID Cont
##1  1    a
##2  1    a
##3  1    b
##4  2    a
##5  2    c
##6  2    d



回答2:


library(data.table)
setDT(x)[, .(Freq = .N), by = .(ID, Cont)]

#     ID Cont Freq
# 1:  1    a    2
# 2:  1    b    1
# 3:  2    a    1
# 4:  2    c    1
# 5:  2    d    1



回答3:


With base R:

df1 <- subset(as.data.frame(table(df)), Freq != 0)

if you want to order by ID, add this line:

df1[order(df1$ID)]

   ID Cont Freq
1  1    a    2
3  1    b    1
2  2    a    1
6  2    c    1
8  2    d    1


来源:https://stackoverflow.com/questions/40378299/r-frequency-with-group-by-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!