Find most recent Monday for a dataframe

前端 未结 6 626
甜味超标
甜味超标 2021-01-15 02:35

I have a dataframe object, and among the fields in it, I have a dates:

df$dates

I need to add a column which is \'Week Starting\', i.e.

6条回答
  •  粉色の甜心
    2021-01-15 03:13

    If you want nearest any day and hour to the current date, use this function:

    dayhour <- function(day,hour){
       k <- as.Date(Sys.time())+day-as.numeric(format(strptime(Sys.time(),format="%Y-%m-%d %H:%M:%S"), format ='%u'))
       dh <- format(strptime(paste(k,hour), format="%Y-%m-%d %H"), format="%A %H")
       return(dh)
    }
    

    For the weekdays use 0 to 6 as day argument for sunday to saturday respectively:

    > dayhour(0,17)
    [1] "Sunday 17"
    

提交回复
热议问题