'How to get the average temperature for N days prior to a specific date in R?

I have two datasets: one dataset (A) has the temperatures for each day, and on the other dataset (B) I have the individuals id and the date of birth (dob). I need to get the average temperature for the last 3 days prior to the dob of each individual. For example: if individual 1 was born in 02/20/2021, I need the average temperature from 02/17/2021 to 02/19/2021. Is there a way I could do that in R so my output would be ind | dob | avg_temp. Here is one example data (in my real case, my data has a very large number of days and individuals):

> temp <- c(26,27,28,30,32,27,28,29)
> date <- as.Date(c('02-15-2021', '02-16-2021', '02-17-2021', '02-18-2021', '02-19-2021', '02-20-2021', '02-21-2021',
+ '02-22-2021'), "%m-%d-%Y")
> A <- data.frame(date, temp)
> id <- c(1,2,3,4,5,6,7,8,9,10)
> dob <- as.Date(c('02-18-2021', '02-17-2021', '02-20-2021', '02-23-2021', '02-25-2021', '02-23-2021', '02-17-2021',
+                  '02-25-2021', '02-25-2021', '02-23-2021'), "%m-%d-%Y")
> B <- data.frame(id, dob) 

In case the date does not have full 3 days, it would do the average with the number of days avaialble (2 or 1), and if no day is available it would return 0 as the average.

Does anyone could help me do this in R? As I mentioned above, my dateset is quite large, with ~37,000 ids, and temperatures ranging from 2007 to 2021.

Thank you in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source