如何按組將唯一值的計數添加到R數據中。我希望通過分組第二個變量來計數唯一值的數量,然后將計數作為一個新列添加到現有的data.framework中。例如,如果現有的數據框架如下所示: color type1 black chair2 black chair3 black sofa4 green sofa5 green sofa6 red sofa7 red plate8 blue sofa9 blue plate10 blue chair我想為每個color,唯一的數types現有數據: color type unique_types1 black chair 22 black chair 23 black sofa 24 green sofa 15 green sofa 16 red sofa 27 red plate 28 blue sofa 39 blue plate 310 blue chair 3我希望用ave,但似乎找不到一個直接的方法,不需要很多行。我有>100,000行,所以我也不確定效率有多重要。它有點類似于這個問題:每組計數觀察/行數,并將結果添加到數據幀中
3 回答

慕尼黑5688855
TA貢獻1848條經驗 獲得超2個贊
ave
within(df, { count <- ave(type, color, FUN=function(x) length(unique(x)))})
type
data.table
require(data.table)setDT(df)[, count := uniqueN(type), by = color] # v1.9.6+# if you don't want df to be modified by referenceans = as.data.table(df)[, count := uniqueN(type), by = color]
uniqueN
v1.9.6
length(unique(.))
require(plyr)ddply(df, .(color), mutate, count = length(unique(type)))
aggregate
:
agg <- aggregate(data=df, type ~ color, function(x) length(unique(x)))merge(df, agg, by="color", all=TRUE)

holdtom
TA貢獻1805條經驗 獲得超10個贊
unique
table
tabulate
df$color
factor
table(unique(df)$color)[as.character(df$color)]# black black black green green red red blue blue blue # 2 2 2 1 1 2 2 3 3 3
tabulate(unique(df)$color)[as.integer(df$color)]# [1] 2 2 2 1 1 2 2 3 3 3
df$color
character
table(unique(df)$color)[df$color]
df$color
integer
tabulate(unique(df)$color)[df$color]
- 3 回答
- 0 關注
- 806 瀏覽
添加回答
舉報
0/150
提交
取消