ID= c('A', 'A', 'A', 'B', 'B', 'B')
color=c('white', 'green', 'orange', 'white', 'green', 'green')
d = data.frame (ID, color)
Run Code Online (Sandbox Code Playgroud)
我想要的结果是
unique_colors=c(3,3,3,2,2,2)
d = data.frame (ID, color, unique_colors)
Run Code Online (Sandbox Code Playgroud)
或者在新的数据框架中更清楚c
ID= c('A','B')
unique_colors=c(3,2)
c = data.frame (ID,unique_colors)
Run Code Online (Sandbox Code Playgroud)
我试过的不同组合aggregate和ave以及by和with我想这是这些功能的组合.
解决方案包括:
length(unique(d$color))
Run Code Online (Sandbox Code Playgroud)
计算唯一元素的数量.
Dav*_*urg 70
我想你在这里弄错了.使用时plyr或<-使用时都不需要data.table.
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
Run Code Online (Sandbox Code Playgroud)
如果要使用计数创建新列,请使用:=运算符
setDT(d)[, count := uniqueN(color), by = ID]
Run Code Online (Sandbox Code Playgroud)
或者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
Run Code Online (Sandbox Code Playgroud)
或者(如果你想要一个新列)使用mutate而不是summary
d %>%
group_by(ID) %>%
mutate(count = n_distinct(color))
Run Code Online (Sandbox Code Playgroud)