How can I create a dataframe calculated with other dataframes?

I have two dataframes, the first (df1) only with dates and the second (df2) with dates and values -> see example.
I want to create a third dataframe (df3) with the dates from df1 where the values from df2 are averaged in the period between the dates from df1.
Unfortunatly there is no structured continuity of the dates.

So the result should be:

1986-01-15      NA
1986-01-20      (6+8+1)/3 = 5
1986-01-24      (7+3+9+1)/4 = 5
1986-01-28      (4+5)/2 = 4,5
df1 <- data.frame(
  Date = c(
    "1986-01-15",
    "1986-01-20",
    "1986-01-24",
    "1986-01-28"
  )
)
View(df1)

df2 <- data.frame(
  Date = c(
    "1986-01-16",
    "1986-01-17",
    "1986-01-20",
    "1986-01-21",
    "1986-01-22",
    "1986-01-23",
    "1986-01-24",
    "1986-01-27",
    "1986-01-28"
  ),
  Value = c(6,8,1,7,3,9,1,4,5)
)
View(df2)

I hope someone can help. Thank youu!!

library(tidyverse)

df1 <- data.frame(
  Date = c(
    "1986-01-15",
    "1986-01-20",
    "1986-01-24",
    "1986-01-28"
  )
) |> mutate_all(as.Date)

df2 <- data.frame(
  Date = c(
    "1986-01-16",
    "1986-01-17",
    "1986-01-20",
    "1986-01-21",
    "1986-01-22",
    "1986-01-23",
    "1986-01-24",
    "1986-01-27",
    "1986-01-28"
  ),
  Value = c(6, 8, 1, 7, 3, 9, 1, 4, 5)
) |> mutate_at(
  .vars = "Date",
  .funs = as.Date
)

seq_or_sing <- function(f, t) {
  if (is.na(t)) {return(t)}
  if (identical(f, t)) {return(f)}
  seq.Date(
    from = f,
    to = t + 1,
    by = -1
  )
}

(df1x <- mutate(df1,
  keydate = Date,
  prevDate = lag(Date, 1)
) |>
  rowwise() |>
  mutate(
    dates = list(seq_or_sing(Date, prevDate))
  ) |> select(
    keydate, dates
  )
  |> ungroup() |> unnest_longer(col = dates) |>
  arrange(keydate, dates))

(df3_a <- left_join(df1x,
  df2,
  by = c("dates" = "Date")
))
(df3_b <- df3_a |>
  group_by(keydate) |>
  summarise(
    sv = sum(Value, na.rm = TRUE),
    cnt = sum(!is.na(Value)),
    avg = sv / cnt
  ))

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.