如何按组将唯一值的计数添加到R数据中。

如何按组将唯一值的计数添加到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行,所以我也不确定效率有多重要。

它有点类似于这个问题:每组计数观察/行数,并将结果添加到数据帧中


慕森卡
浏览 729回答 3
3回答

慕尼黑5688855

使用ave(既然你特别要求):within(df,&nbsp;{&nbsp;count&nbsp;<-&nbsp;ave(type,&nbsp;color,&nbsp;FUN=function(x)&nbsp;length(unique(x)))})确保type是字符向量而不是因子。因为您还说您的数据是巨大的,因此速度/性能可能是一个因素,我建议data.table也有解决办法。require(data.table)setDT(df)[,&nbsp;count&nbsp;:=&nbsp;uniqueN(type),&nbsp;by&nbsp;=&nbsp;color]&nbsp;#&nbsp;v1.9.6+#&nbsp;if&nbsp;you&nbsp;don't&nbsp;want&nbsp;df&nbsp;to&nbsp;be&nbsp;modified&nbsp;by&nbsp;referenceans&nbsp;=&nbsp;as.data.table(df)[,&nbsp;count&nbsp;:=&nbsp;uniqueN(type),&nbsp;by&nbsp;=&nbsp;color]uniqueN在v1.9.6是一个更快的等价物length(unique(.))..此外,它还可以处理data.framework/data.table。其他解决办法:使用plyr:require(plyr)ddply(df,&nbsp;.(color),&nbsp;mutate,&nbsp;count&nbsp;=&nbsp;length(unique(type)))使用aggregate:agg&nbsp;<-&nbsp;aggregate(data=df,&nbsp;type&nbsp;~&nbsp;color,&nbsp;function(x)&nbsp;length(unique(x)))merge(df,&nbsp;agg,&nbsp;by="color",&nbsp;all=TRUE)

噜噜哒

下面是一个解决方案dplyr包裹-它有n_distinct()作为包装length(unique()).df&nbsp;%>% &nbsp;&nbsp;group_by(color)&nbsp;%>% &nbsp;&nbsp;mutate(unique_types&nbsp;=&nbsp;n_distinct(type))

holdtom

这也可以在没有组操作的向量化中实现,方法是unique带着table或tabulate如果df$color是factor,然后任一table(unique(df)$color)[as.character(df$color)]#&nbsp;black&nbsp;black&nbsp;black&nbsp;green&nbsp;green&nbsp;&nbsp;&nbsp;red&nbsp;&nbsp;&nbsp;red&nbsp;&nbsp;blue&nbsp;&nbsp;blue&nbsp;&nbsp;blue&nbsp;#&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3或tabulate(unique(df)$color)[as.integer(df$color)]#&nbsp;[1]&nbsp;2&nbsp;2&nbsp;2&nbsp;1&nbsp;1&nbsp;2&nbsp;2&nbsp;3&nbsp;3&nbsp;3如果df$color是character然后.table(unique(df)$color)[df$color]如果df$color是integer然后.tabulate(unique(df)$color)[df$color]
打开App,查看更多内容
随时随地看视频慕课网APP