【问题标题】:Calculate Mean for Each Unique Value up to a certain date计算截至特定日期的每个唯一值的平均值
【发布时间】:2021-07-13 19:06:45
【问题描述】:

我的例子的数据。

date1 = seq(as.Date("2019/01/01"), by = "month", length.out = 48)
date2 = seq(as.Date("2019/02/01"), by = "month", length.out = 48)
date3 = seq(as.Date("2019/02/01"), by = "month", length.out = 48)
date4 = seq(as.Date("2019/02/01"), by = "month", length.out = 48)
date = c(date1,date2,date3,date4)



subproducts1=rep("1",48)
subproducts2=rep("2",48)
subproductsx=rep("x",48)
subproductsy=rep("y",48)

b1 <- c(rnorm(48,5))
b2 <- c(rnorm(48,5))
b3 <-c(rnorm(48,5) )
b4 <- c(rnorm(48,5))

dfone <- data.frame(
                "date"= date,
               
                "subproduct"= 
                  c(subproducts1,subproducts2,subproductsx,subproductsy),
                "actuals"= c(b1,b2,b3,b4))

这将为 date2、3、4 创建 2019 年 1 月,值为 0。

 dfone <-dfone %>%
 complete(date = seq.Date(from = min(date), to = as.Date('2021-06-01'), by = 'month'), 
       nesting(subproduct), fill = list(actuals = 0))

问题:这会计算每个唯一子产品的平均值,并将 0 替换为每个子产品的平均值,但是我如何设置硬截止值,所以平均值仅基于 2019 年 1 月至 2020 年 12 月,而不是 2019 年 1 月至2022 年 12 月?

library(dplyr)
dfone_new <- dfone %>%
     group_by(subproduct)  %>%
     mutate(actuals = replace(actuals, actuals == 0, 
         mean(actuals[actuals != 0], na.rm = TRUE))) %>%
     ungroup

【问题讨论】:

    标签: r dplyr data-manipulation


    【解决方案1】:

    在对“实际值”进行子集化时,我们可能还需要一个逻辑表达式,即“日期”应为 between 2019 年 1 月和 2020 年 12 月,同时计算 mean

    library(dplyr)
    library(tidyr)
    dfone %>%
         group_by(subproduct)  %>%
         mutate(actuals = replace(actuals, actuals == 0, 
             mean(actuals[actuals != 0  & 
        between(date, as.Date("2019-01-01"), as.Date("2020-12-31"))], 
             na.rm = TRUE)))
    

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 2015-07-28
      • 1970-01-01
      • 2020-06-04
      相关资源
      最近更新 更多