计算一组中不同变量的数量

count the number of distinct variables in a group

我有一个这样的数据框:

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))

其中 return 个:

    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

我想 return 一个 table 指示变量是否在组中表示:

Group V1 V2 V3
A     1  0  1
B     1  1  1

为了统计每组不同变量的个数。

你试过了吗

unique(group_by(mtcars,cyl)$cyl).  

Output:[1] 6 4 8

我们可以用 base R

aggregate(.~Group, df[-1], function(x) as.integer(sum(x)>0))
#  Group V1 V2 V3
#1     A  1  0  1
#2     B  1  1  1

或使用 base R

中的 rowsum
+(rowsum(df[-(1:2)], df$Group)>0)
#   V1 V2 V3
#A  1  0  1
#B  1  1  1

by 来自 base R

+(do.call(rbind, by(df[3:5], df['Group'], FUN = colSums))>0)
#   V1 V2 V3
#A  1  0  1
#B  1  1  1