R data.table set new column with logical value if a weekday is between a date range

前端 未结 3 1083
萌比男神i
萌比男神i 2021-01-15 09:54

I have a data.table object with two date columns, from and to. I want to create a new column to determine if a specific w

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 10:32

    Here's my example:

    library(parallel)
    
    process <- function(){
    
    
      from <- seq(as.Date("1950-01-01"), by = "day", length = 100000)
      to <- seq(as.Date("1950-01-04"), by = "day", length = 100000)
    
      DT <- data.frame(from,to)
    
      Ncores <- detectCores()
    
      flagList <- mclapply(1:nrow(DT),function(id){
    
        4 %in% strftime(seq(as.Date(DT[id,1]), as.Date(DT[id,2]), by="day"), format="%w")
    
      },mc.cores=Ncores)
    
      flag <- unlist(flagList)
    
      return(cbind(DT,flag))
    
    }
    

    It takes just 15 sec for 100k rows on my i7 processor. Hope this helps.

提交回复
热议问题