【问题标题】:How to count the number of unique values by group? [duplicate]如何按组计算唯一值的数量? [复制]
【发布时间】:2015-01-27 15:10:25
【问题描述】:
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

ID= c('A','B')
unique_colors=c(3,2)
c = data.frame (ID,unique_colors)

我尝试了 aggregate 和 ave 以及 by 和 with 的不同组合,我想这是这些功能的组合。

解决方案包括:

length(unique(d$color))

计算唯一元素的数量。

【问题讨论】:

  • 另请参阅 here,(在 Q 上的标题有点相似......你在发布之前搜索过吗?)以获取更多可能性

标签: r


【解决方案1】:

我认为你在这里搞错了。使用data.table时,plyr或<-都不需要。

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

如果要使用计数创建新列,请使用 := 运算符

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

d %>%
  group_by(ID) %>%
  mutate(count = n_distinct(color))

【讨论】:

  • 一个穷人的功能是with(d, ave(as.numeric(color), ID, FUN=function(x) length(unique(x))))
  • @akrun 您可以将其发布为替代方案。
  • @DavidArenburg David,也许在遗漏了一些明显的东西,但我正在尝试将 uniqueN 与最新版本的 data.table 一起使用,并且说该包不存在。你有什么想法
  • @MatthewR 是的,正如我所提到的,此功能仅存在于 GitHub 上的开发版本中。请点击我提供的链接。
  • 这也有效:d %>% group_by(ID) %>% mutate(count = n())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-16
  • 2018-02-20
  • 1970-01-01
相关资源
最近更新 更多