I'm not sure how to ask this one unfortunately but I think there has got to be easier solution than the one I came up with.
Below I have df1
which has daily data measuring variable x
. There is also df2
which is annual with a column referring to the day of year. I'd like to extract x
from df1
on the day of year specified in df2
. E.g., in the year 1990 the flagged day of the year in df2
is 101. I want to get the value of x
on the 101st day of 1990 from df1
and so on for every year. I wrote a loop that accomplishes this but there has to be a better way. Any help appreciated.
library(tidyverse)
library(lubridate)
set.seed(123)
df1 <- tibble(Date=seq(as.Date("1990/1/1"), as.Date("1999/12/31"), "days")) %>%
mutate(Year = year(Date)) %>%
mutate(DOY = yday(Date)) %>%
group_by(Year) %>%
mutate(x = cumsum(runif(n())))
df2 <- tibble(Year = seq(1990,1999),
DOY = c(101,93,94,95,88,100,102,200,301,34),
x=NA)
df1 %>% filter(Year == 1990, DOY == 101) %>% pull(x)
for(i in 1:10){
df2$x[i] <- df1 %>% filter(Year == df2$Year[i],
DOY == df2$DOY[i]) %>% pull(x)
}
df2