我有一个这样的数据框:
ID Cont
1 a
1 a
1 b
2 a
2 c
2 d
我需要通过ID报告“Cont”的频率。输出应为
ID Cont Freq
1 a 2
1 b 1
2 a 1
2 c 1
2 d 1
答案 0 :(得分:5)
使用dplyr
,group_by
和ID
以及Cont
summarise
使用n()
获取Freq
:< / p>
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
数据:强>
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
答案 1 :(得分:3)
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
答案 2 :(得分:3)
以基地R:
var response = JSON.parse(responseBody);
response["#!#"].forEach( function(entry) {
test["foo"] = entry._type === "application";
...
});
如果您想按ID排序,请添加以下行:
df1 <- subset(as.data.frame(table(df)), Freq != 0)