第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何按組將唯一值的計(jì)數(shù)添加到R數(shù)據(jù)中。

如何按組將唯一值的計(jì)數(shù)添加到R數(shù)據(jù)中。

慕森卡 2019-06-26 13:45:55
如何按組將唯一值的計(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是字符向量而不是因子。


因?yàn)槟€說您的數(shù)據(jù)是巨大的,因此速度/性能可能是一個(gè)因素,我建議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]

uniqueNv1.9.6是一個(gè)更快的等價(jià)物length(unique(.))..此外,它還可以處理data.framework/data.table。


其他解決辦法:

使用plyr:

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)


查看完整回答
反對(duì) 回復(fù) 2019-06-26
?
嚕嚕噠

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊

下面是一個(gè)解決方案dplyr包裹-它有n_distinct()作為包裝length(unique()).

df %>%
  group_by(color) %>%
  mutate(unique_types = n_distinct(type))


查看完整回答
反對(duì) 回復(fù) 2019-06-26
?
holdtom

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊

這也可以在沒有組操作的向量化中實(shí)現(xiàn),方法是unique帶著tabletabulate

如果df$colorfactor,然后

任一

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$colorcharacter然后.

table(unique(df)$color)[df$color]

如果df$colorinteger然后.

tabulate(unique(df)$color)[df$color]


查看完整回答
反對(duì) 回復(fù) 2019-06-26
  • 3 回答
  • 0 關(guān)注
  • 798 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)