r 分组和计数

标签 r group-by dplyr plyr reshape2

我正在处理如下数据集

      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 Row , 2nd 列(Representation)中的值为 3,因为 Red 基于 ID 和 Date 的唯一组合表示了 3 次。例如,1st 和 2nd 行是相同的,Id(10) 和 Date(2008-11-17) 所以这个组合表示一次(1(10,2008-11-17))。第 4th 和 7th 行是相同的 Id(10) 和 Date(2010-01-26) 组合,因此这种唯一组合表示一次 (1<子>(10, 2010-01-26)) 。第 8th、9th、12th 是 Id(29) 和 Date(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

计数

第 1st 行,第 3rd 列(计数)中的值为 7,因为 ID 102008-11-17 (2 10, 2008-11-17),在 2010- 上 ID 10 再次提到 Red 两次01-26 (2 10, 2010-01-26) 和 3 次 ID 29 on 2007-07-31 2 29,2007-07-31

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)  

最佳答案

使用 dplyr:

library(dplyr)
dat %>% group_by(Color) %>%
    summarize(Representation = n_distinct(Id, Date), Count = n())
# # A tibble: 3 × 3
#    Color Representation Count
#   <fctr>          <int> <int>
# 1   Blue              2     2
# 2  Green              2     3
# 3    Red              3     7

关于r 分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40118936/

相关文章:

r - 如何修改 dplyr 函数以免出现错误 : Column `column` is unknown?

r - 将 knitr::kable() 输出保存到 html 文件 R

r - R中的Shapefile到光栅转换?

mysql - 每半个月日期范围分组

mysql - 每个唯一列值获取一条记录

替换按年份命名的有序列中的值(来自指示范围的列)

r - 从 dplyr 管道生成直方图

r - 将数据从 xml 转换为 R 数据框

r - 如何根据最小样本量在 R 中对数据框进行子集化

mysql - SQL : a GROUP BY issue in MySQL