怎么办SUMIFS中的R(How to do SUMIFS in R)

2019-09-26 06:39发布

数据:

 set.seed(42)

df1 = data.frame(
  Date = seq.Date(as.Date("2018-01-01"),as.Date("2018-01-30"),1),
  value = sample(1:30),
  Y = sample(c("yes", "no"), 30, replace = TRUE)
)

df2 = data.frame(
  Date = seq.Date(as.Date("2018-01-01"),as.Date("2018-01-30"),7)
)

我想在每个日期df2$Date计算DF1 $值的总和,如果日期df1$Date落入df2$Datedf2$Date +6

Inshort我需要计算每周总和

Answer 1:

使用data.table,创建范围的开始/结束,然后在重叠合并,然后得到求和组:

library(data.table)

df1$start <- df1$Date
df1$end <- df1$Date

df2$start <- df2$Date
df2$end <- df2$Date + 6

setDT(df1, key = c("start", "end"))
setDT(df2, key = c("start", "end"))

foverlaps(df1, df2)[, list(mySum = sum(value)), by = Date ]
#          Date mySum
# 1: 2018-01-01   138
# 2: 2018-01-08    96
# 3: 2018-01-15    83
# 4: 2018-01-22   109
# 5: 2018-01-29    39


Answer 2:

检查出库lubridate和dplyr,这两个是安静常见。

library(lubridate)
library(dplyr)

df1$last_week_day <- ceiling_date(df1$Date, "week") + 1
df1 %>% group_by(last_week_day) %>% summarize(week_value = sum(value))


Answer 3:

我们可以使用fuzzyjoin

library(dplyr)
library(fuzzyjoin)

df2$EndDate <- df2$Date+6

fuzzy_left_join(
  df1, df2,
  by = c(
    "Date" = "Date",
    "Date" = "EndDate"
  ), match_fun = list(`>=`, `<=`)) %>% 
  group_by(Date.y) %>% summarise(Sum=sum(value))


# A tibble: 5 x 2
     Date.y       Sum
     <date>     <int>
  1 2018-01-01   138
  2 2018-01-08    96
  3 2018-01-15    83
  4 2018-01-22   109
  5 2018-01-29    39


文章来源: How to do SUMIFS in R
标签: r sumifs