Find most recent Monday for a dataframe

前端 未结 6 640
甜味超标
甜味超标 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:10

    A base R approach with the function strftime.

    df$Week.Start <- dates-abs(1-as.numeric(strftime(df$dates, "%u")))
    

    This can be a one-liner but we'll create a few variables to see what's happening. The %u format pattern for dates returns the day of the week as a single decimal number. We can convert that number to numeric and subtract the distance from our dates. We can then subtract that vector from our date column.

    day_of_week <- as.numeric(strftime(df$dates, "%u"))
    day_diff <- abs(1-day_of_week)
    df$Week.Start <- dates-day_diff
    #        dates Week.Start
    # 1 2042-10-22 2042-10-20
    # 2 2026-08-14 2026-08-10
    # 3 2018-11-23 2018-11-19
    # 4 2017-08-21 2017-08-21
    # 5 2022-05-26 2022-05-23
    # 6 2037-05-27 2037-05-25
    

    Data

    set.seed(7)
    all_dates <- seq(Sys.Date(), Sys.Date()+10000, by="days")
    dates <- sample(all_dates, 20)
    df <- data.frame(dates)
    

提交回复
热议问题