如何按组计算唯一值的数量? [英] How to count the number of unique values by group?
问题描述
ID= c('A', 'A', 'A', 'B', 'B', 'B')
color=c('white', 'green', 'orange', 'white', 'green', 'green')
d = data.frame (ID, color)
我想要的结果是
unique_colors=c(3,3,3,2,2,2)
d = data.frame (ID, color, unique_colors)
或者在新的数据框 c 中更清楚
or more clear in a new dataframe c
ID= c('A','B')
unique_colors=c(3,2)
c = data.frame (ID,unique_colors)
我尝试了 aggregate
和 ave
以及 by
和 with
的不同组合,我想它是这些功能的组合.
I've tried different combinations of aggregate
and ave
as well as by
and with
and I suppose it is a combination of those functions.
解决方案包括:
length(unique(d$color))
计算唯一元素的数量.
推荐答案
我认为你在这里弄错了.使用 data.table
时,plyr
或 <-
中都不需要.
I think you've got it all wrong here. There is no need neither in plyr
or <-
when using data.table
.
data.table 的最新版本,v >= 1.9.6,有一个新函数 uniqueN()
就是为了这个.
Recent versions of data.table, v >= 1.9.6, have a new function uniqueN()
just for that.
library(data.table) ## >= v1.9.6
setDT(d)[, .(count = uniqueN(color)), by = ID]
# ID count
# 1: A 3
# 2: B 2
如果要创建包含计数的新列,请使用 :=
运算符
If you want to create a new column with the counts, use the :=
operator
setDT(d)[, count := uniqueN(color), by = ID]
<小时>
或者与 dplyr
一起使用 n_distinct
函数
library(dplyr)
d %>%
group_by(ID) %>%
summarise(count = n_distinct(color))
# Source: local data table [2 x 2]
#
# ID count
# 1 A 3
# 2 B 2
或者(如果你想要一个新列)使用 mutate
而不是 summary
Or (if you want a new column) use mutate
instead of summary
d %>%
group_by(ID) %>%
mutate(count = n_distinct(color))
这篇关于如何按组计算唯一值的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!