My two data frames are accessible here and here and I have been trying to follow this previous post.
I would like to populate wombat$rainfall_lag_2wk
with the sum of rainfall records for the previous two weeks/14 days, this data is available in rain
. I have tried to do this a number of ways before I found the above post. Most recently I have tried to follow the above post, but I get the below error.
Any help would be greatly appreciated. I am happy with any solution, whether it follows the same structure as the above post or not.
Thanks in advance
# Load data
wombat <- read.csv("wombat.csv", header = TRUE)
rain <- read.csv("rain.csv", header = TRUE)
# Define dates
wombat$date <- as.Date(wombat$date, "%Y-%m-%d")
rain$Date <- as.Date(rain$Date, "%Y-%m-%d")
# Calculate rainfall for previous two weeks following above link
wombat$start_date <- rep_len("01/01/1970", nrow(wombat))
wombat$start_date <- as.Date(wombat$start_date, "%m/%d/%Y")
wombat$diff_days <- as.numeric(difftime(wombat$date, wombat$start_date, units = "days"))
rain$start_date <- rep_len("01/01/1970", nrow(rain))
rain$start_date <- as.Date(rain$start_date, "%m/%d/%Y")
rain$diff_days <- as.numeric(difftime(rain$Date, rain$start_date, units = "days"))
for (i in 1:length(wombat$diffdays)) {
day = wombat$diffdays[i]
rainday = pmatch(day, rain$diffdays, dup = FALSE)
wombat$rainfall_lag_2wk[i] = sum(rain$Rainfall.amount..millimetres.[(rainday-14):(rainday-1)]) # 14 days
}
Error after running above Error in (rainday - 14):(rainday - 1) : argument of length 0