如何按組將唯一值的計(jì)數(shù)添加到R數(shù)據(jù)中。我希望通過分組第二個(gè)變量來計(jì)數(shù)唯一值的數(shù)量,然后將計(jì)數(shù)作為一個(gè)新列添加到現(xiàn)有的data.framework中。例如,如果現(xiàn)有的數(shù)據(jù)框架如下所示: color type1 black chair2 black chair3 black sofa4 green sofa5 green sofa6 red sofa7 red plate8 blue sofa9 blue plate10 blue chair我想為每個(gè)color,唯一的數(shù)types現(xiàn)有數(shù)據(jù): 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,但似乎找不到一個(gè)直接的方法,不需要很多行。我有>100,000行,所以我也不確定效率有多重要。它有點(diǎn)類似于這個(gè)問題:每組計(jì)數(shù)觀察/行數(shù),并將結(jié)果添加到數(shù)據(jù)幀中
3 回答

慕尼黑5688855
TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
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貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
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 關(guān)注
- 798 瀏覽
添加回答
舉報(bào)
0/150
提交
取消