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

前端 未结 3 1106
萌比男神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条回答
  •  时光取名叫无心
    2021-01-15 10:26

    You could also try the foverlaps approach

    First will create data set of all the Wednesday starting from min(from) and ending at max(to)

    DateDT <- DT[, {
                    temp <- seq(min(from), max(to), by = "day")
                    temp2 <- temp[wday(temp) == 4L]
                    .(from = temp2, to = temp2)
                   }
                 ]
    

    Then run foverlaps and extract desired rows

    indx <- foverlaps(DT, setkey(DateDT), nomatch = 0L, which = TRUE)$xid
    

    Then a simple update by reference will do

    DT[, flag := 0L][indx, flag := 1L]
    DT[, table(flag)]
    #  0  1 
    # 44 57 
    

提交回复
热议问题