如何在R中做SUMIFS

时间:2019-03-26 09:48:36

标签: r sumifs

数据:

 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$Datedf2$Date + 6之内,我想为df2$Date中的每个日期计算df1 $ Value的总和。

简而言之,我需要计算每周金额

3 个答案:

答案 0 :(得分:0)

查看库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))

答案 1 :(得分:0)

使用 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

答案 2 :(得分:0)

我们可以使用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