Reproducible Data:
df1 <- tibble(id = c("GR1","GR2"),
area = c("A1","A2"),
date1 = as.Date(c("2022-01-01","2022-01-02")),
date2 = as.Date(c("2022-01-06","2022-01-08")))
set.seed(543)
df2 <- tibble(date3 = seq(as.Date("2022-01-01"), as.Date("2022-01-09"), "days"),
temperature =runif(9, min = 28, max = 33),
area = c("A1","A2","A1","A2","A1","A2","A1","A2","A1"))
Hello, I want to create a column in df1 with the average temperature resulting in a filter from df2. (In the real data frames I have 1036 rows in df1 and 26192 rows in df2. )
I tried this approach, but it doesn't work as I thought
df3 <- df1 %>%
group_by(area) %>%
mutate(average_temp = mean(filter(.data = df2, date3 >= df1$date1 & date3 <= df1$date2 & area == df1$area)$temperature))
I get this error
Warning messages:
1: Problem while computing average_temp = mean(...).
i longer object length is not a multiple of shorter object length
The expected result is
| id | area | date1 | date2 | average_temp |
|---|---|---|---|---|
| GR1 | A1 | 2022-01-01 | 2022-02-12 | 31.58708 |
| GR2 | A2 | 2022-01-02 | 2022-02-11 | 30.50867 |
This chunk of code by itself gives the expected result. So the problem must be something I'm not seeing in the iteration of rows withing the logic in mutate and dplyr syntax.
mean(filter(.data = df2, date3 >= df1$date1[2] & date3 <= df1$date2[2] & area == df1$area[2])$temperature)