【问题标题】:Aggregate based on condition and date根据条件和日期汇总
【发布时间】:2017-09-25 13:52:16
【问题描述】:

我有一个如下所示的每日数据集:

date       CMA0013 CMA0047 CMA0052 CMA0067
1975-10-01       0   0.012   0.078       0
1975-10-02       0   0.012   0.078       0
1975-10-03       0   0.012   0.078       0
1975-10-04       0   0.012   0.078       0
1975-10-05       0   0.012   0.078       0
1975-10-06       0   0.012   0.078       0
...

在 R 中,我想按月和年计算(汇总)每列中有多少条记录满足条件< 0.001。假设得到类似的东西:

month   year    CMA0013   CMA0047   CMA0052   CMA0067
   10   1975          6         0         0         6
   11   1975        ...

我尝试了使用aggregateddply 函数的不同选项,但是由于我对它们的了解还不是很深,所以我无法得到任何令人满意的解决方案。感谢大家提供的任何帮助

一个不适用于ddply的例子

df$year <- year(df$date)
df$month <- month(df$date)

df2 <- ddply(df,~year+month,summarise,
count = length(df[,df$CMA0010 < 0.001]))

它没有正确地求和,它只对一列进行求和 (CMA0010)

【问题讨论】:

  • 欢迎来到 SO。请展示您已经尝试过的内容(以及不适合您的内容),以便 SO 用户可以看到您的一些研究工作。
  • 感谢您的评论和建议。我做了一堆研究,(一整天是否足够?),并尝试调整其他相关帖子的解决方案,以解决我的问题,但找不到令人满意的解决方案。我接受您的建议,并将在以后的帖子中展示我的尝试。干杯
  • 真的很难说什么是“足够”,这一直是广泛元讨论的话题。尽管如此,这个想法是为了防止人们来到这里并在不付出任何努力的情况下寻求完整的解决方案。如果您觉得您的网络搜索引擎研究已经筋疲力尽,那么 SO 就是您的最佳选择。这就是为什么预计会在问题中显示一些具体的尝试。
  • 我完全理解。的确,经过一番艰苦的斗争,发帖是我的终极资源。我编辑了我的帖子以展示我不满意的尝试之一。无论如何,我很感激你的建议
  • 是的,谢谢,干得好!

标签: r date dplyr


【解决方案1】:

这是一种方法...

library(lubridate) #to extract the year and month
df$year <- year(df$date)
df$month <- month(df$date)
df2 <- aggregate(df[, grep("CMA", names(df))], #just summarise columns starting "CMA"
                 by = list(year=df$year, month=df$month), 
                 function(x) sum(x<0.001))

df2
  year month CMA0013 CMA0047 CMA0052 CMA0067
1 1975    10       6       0       0       6

【讨论】:

    【解决方案2】:

    尝试将 lubridate 包与 dplyr 一起使用:

       sum_df <- daily %>%
          mutate(month = lubridate::month(date),
                   year= lubridate::year(date)) %>%
          group_by(year, month) %>%
          summarise(CMA0013 = sum(CMA0013 < 0.001),
                    #The rest of you sums...
                    )
    

    【讨论】:

      【解决方案3】:

      dplyrlubridate 解决方案,但自动计算所有 CMA 列的总和。

      library(dplyr)
      library(lubridate)
      library(tidyr)
      d %>%
          gather(key, value, -date) %>%
          mutate(year = year(date), month = month(date)) %>%
          select(-date) %>%
          group_by(year, month, key) %>%
          summarize(N = sum(value < 0.001)) %>%
          spread(key, N)
      
      # A tibble: 1 x 6
      # Groups:   year, month [1]
         year month CMA0013 CMA0047 CMA0052 CMA0067
      * <dbl> <dbl>   <int>   <int>   <int>   <int>
      1  1975    10       6       0       0       6
      

      【讨论】:

      • 谢谢,大部分语法我都不熟悉(尤其是%>%),不过会努力学习的
      猜你喜欢
      • 2023-03-23
      • 2016-12-30
      • 2019-06-12
      • 1970-01-01
      • 2021-08-25
      • 2019-03-06
      • 2021-06-28
      • 2021-07-20
      • 1970-01-01
      相关资源
      最近更新 更多