Check if a date is within an interval in R

前端 未结 6 921
暗喜
暗喜 2020-11-30 12:48

I have these three intervals defined:

YEAR_1  <- interval(ymd(\'2002-09-01\'), ymd(\'2003-08-31\'))
YEAR_2  <- interval(ymd(\'2003-09-01\'), ymd(\'20         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 13:38

    You can use walk from package purrr for this:

    purrr::walk(1:3, ~(df$Year[as.POSIXlt(df$DATE) %within% get(paste0("YEAR_", .))] <<- .))
    

    or maybe you should write a loop to improve readability (unless taboo for you):

    df$YR <- NA
    for(i in 1:3){
      interval <- get(paste0("YEAR_", i))
      index <-which(as.POSIXlt(df$DATE) %within% interval)
      df$YR[index] <- i
    }
    

提交回复
热议问题