This question already has an answer here:
这个问题在这里已有答案:
- Counting unique / distinct values by group in a data frame 10 answers
- 在数据框中按组计算唯一/不同的值10个答案
ID= c('A', 'A', 'A', 'B', 'B', 'B')
color=c('white', 'green', 'orange', 'white', 'green', 'green')
d = data.frame (ID, color)
My desired result is
我想要的结果是
unique_colors=c(3,3,3,2,2,2)
d = data.frame (ID, color, unique_colors)
or more clear in a new dataframe c
或者在新的数据框架中更清楚c
ID= c('A','B')
unique_colors=c(3,2)
c = data.frame (ID,unique_colors)
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.
我尝试了不同的聚合和ave以及by和with的组合,我想它是这些函数的组合。
The solution would include:
解决方案包括:
length(unique(d$color))
to calculate the number of unique elements.
计算唯一元素的数量。
1 个解决方案
#1
43
I think you've got it all wrong here. There is no need neither in plyr
or <-
when using data.table
.
我想你在这里弄错了。在使用data.table时,plyr或< - 都不需要。
Recent versions of data.table, v >= 1.9.6, have a new function uniqueN()
just for that.
data.table的最新版本,v> = 1.9.6,只有一个新函数uniqueN()。
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]
Or with dplyr
use the n_distinct
function
或者使用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
Or (if you want a new column) use mutate
instead of summary
或者(如果你想要一个新列)使用mutate而不是summary
d %>%
group_by(ID) %>%
mutate(count = n_distinct(color))
#1
43
I think you've got it all wrong here. There is no need neither in plyr
or <-
when using data.table
.
我想你在这里弄错了。在使用data.table时,plyr或< - 都不需要。
Recent versions of data.table, v >= 1.9.6, have a new function uniqueN()
just for that.
data.table的最新版本,v> = 1.9.6,只有一个新函数uniqueN()。
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]
Or with dplyr
use the n_distinct
function
或者使用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
Or (if you want a new column) use mutate
instead of summary
或者(如果你想要一个新列)使用mutate而不是summary
d %>%
group_by(ID) %>%
mutate(count = n_distinct(color))