我想在分组后使用dplyr中的汇总函数来提取数据框中每个变量的级别数。 这是数据框的复制品:
x=c("A","A","A","A","A","B","B","B","B","C","C","C","D","D","D","E","E")
y=c("a","b","c","a","b","a","b","c","d","c","b","e","b","d","f","a","b")
z=c("x","x","x","y","y","p","p","p","p","t","v","v","m","m","n","o","o")
d=data.frame(x,y,z)
以下是我正在使用的代码
library(dplyr)
d %>%
group_by(x) %>%
summarise(total=n(),
Y=nlevels(y),
Z=nlevels(z))
但是,这会生成Y和Z列,用于汇总数据框中的级别' d'而不是分组数据。
我想要生成的数据框如下所示:
x=c("A","B","C","D","E")
total=c(5,4,3,3,2)
Y=c(3,4,3,3,2)
Z=c(2,1,2,2,1)
d2=data.frame(x,total,Y,Z)
d2
谢谢!
答案 0 :(得分:4)
您需要n_distinct
:
d %>%
group_by(x) %>%
summarise(total = n(),
Y = n_distinct(y),
Z = n_distinct(z))
结果:
# A tibble: 5 x 4
x total Y Z
<fctr> <int> <int> <int>
1 A 5 3 2
2 B 4 4 1
3 C 3 3 2
4 D 3 3 2
5 E 2 2 1