R分组依据和计数 [英] r Group by and count

查看:0
本文介绍了R分组依据和计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的数据集如下

      Id     Date           Color
      10     2008-11-17     Red
      10     2008-11-17     Red
      10     2008-11-17     Blue
      10     2010-01-26     Red
      10     2010-01-26     Green
      10     2010-01-26     Green
      10     2010-01-26     Red
      29     2007-07-31     Red
      29     2007-07-31     Red
      29     2007-07-31     Blue
      29     2007-07-31     Green
      29     2007-07-31     Red

我的目标是创建这样的数据集

     Color      Representation      Count            Min   Max
     Red        1 + 1 + 1  = 3      2 + 2 + 3 = 7    2     3
     Blue       1 + 1      = 2      1 + 1            1     1
     Green      1 +  1     = 2      2 + 1            1     2

表示法

第1st行、第2列(表示法)中的值为3,因为Red根据ID和日期的唯一组合表示三次。例如,第1行和第2行ID(10)和日期(2008-11-17)相同,因此此组合表示一次(1(10,2008-11-17))。第4行和第7行是相同的ID(10)和日期(2010-01-26)组合,因此该唯一组合只表示一次(1(10,2010-01-26))。第8次、第9次、第12次是ID(29)和日期(2007-07-31)的相同组合,并且类似地,这被表示一次(1(29,2007-07-31))。因此,第1行第2列中的值为3。

1(10,2008-11-17)+1(10,2010-10-26)+1(29,2007-07-31)=3

计数

第1行第3列(计数)中的值为7,因为<[2-1](2-10,2008-11-17)上的ID10提到了两次Red,再次在<[2-3](2,10,2010-01-26)上ID10提到了Red,并在2007-07-312上按ID29提到了3次

2(10,2008-11-17)+2(10,2010-10-26)+3(29,2007-07-31)

非常感谢对完成此独特频率/计数表的任何帮助。

数据集

Id   = c(10,10,10,10,10,10,10,29,29,29,29,29) 
Date = c("2008-11-17", "2008-11-17", "2008-11-17","2010-01-26","2010-01-26","2010-01-26","2010-01-26",
         "2007-07-31","2007-07-31","2007-07-31","2007-07-31","2007-07-31") 
Color = c("Red", "Red", "Blue", "Red", "Green", "Green", "Red", "Red", "Red", "Blue", "Green", "Red") 
df = data.frame(Id, Date, Color)  

推荐答案

另一个选项是data.table

library(data.table)
setDT(df)[, .(Representation = uniqueN(paste(Id, Date)), Count = .N) , by = Color]
#     Color Representation Count
#1:   Red              3     7
#2:  Blue              2     2
#3: Green              2     3

更新

对于第二个问题,我们可以尝试

library(matrixStats)
m1 <- sapply(split(df[["Color"]], list(df$Id, df$Date), drop = TRUE),  function(x) table(x))
v1 <- (NA^!m1) * m1
df1 <- data.frame(Color = row.names(m1), Representation = rowSums(m1!=0), 
   Count = rowSums(m1), Min = rowMins(v1, na.rm=TRUE),
    Max = rowMaxs(v1, na.rm=TRUE))
row.names(df1) <- NULL
df1
#   Color Representation Count Min Max
#1  Blue              2     2   1   1
#2 Green              2     3   1   2
#3   Red              3     7   2   3

这篇关于R分组依据和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆