我有一个数据框,如:
df <- data.frame(
ID = c('123','124','125','126'),
Group = c('A', 'A', 'B', 'B'),
V1 = c(1,2,1,0),
V2 = c(0,0,1,0),
V3 = c(1,1,0,3))
返回:
ID Group V1 V2 V3
1 123 A 1 0 1
2 124 A 2 0 1
3 125 B 1 1 0
4 126 B 0 0 3
我想返回一个表,表明变量是否在组中表示:
Group V1 V2 V3
A 1 0 1
B 1 1 1
为了计算每组中不同变量的数量。
答案 0 :(得分:4)
使用:
df %>%
group_by(Group) %>%
summarise_at(vars(V1:V3), funs(as.integer(any(. > 0))))
给出:
# A tibble: 2 × 4
Group V1 V2 V3
<fctr> <dbl> <dbl> <dbl>
1 A 1 0 1
2 B 1 1 1
答案 1 :(得分:0)
可以在data.table
中完成:
require(data.table)
setDT(df)
table <- df[, .(sum(V1) > 0, sum(V2) > 0, sum(V3) > 0), Group]
table
Group V1 V2 V3
1: A TRUE FALSE TRUE
2: B TRUE TRUE TRUE
table[, lapply(.SD, as.integer), Group, .SD=2:4]
Group V1 V2 V3
1: A 1 0 1
2: B 1 1 1