How can I group days into weeks?

前端 未结 3 2273
猫巷女王i
猫巷女王i 2020-12-17 18:39

In R, how can I associate between a vector of dates (days) and weeks?

Edit: \"weeks\" should be the week index within the date range and not within the year. My apol

3条回答
  •  别那么骄傲
    2020-12-17 19:21

    For each date, get the week of the year it belongs to by formatting it via format() using the %U of %W format placeholders. %U treats Sunday as the first day of the week, whereas %W considers Monday to be the first day of the week. Here is an example:

    now <- as.Date(Sys.time())
    dates <- seq(now, now + 25, by = "1 day") 
    
    dat <- data.frame(Dates = dates, Week = format(dates, format = "%W"))
    head(dat, 10)
    

    Which gives:

    > head(dat, 10)
            Dates Week
    1  2011-11-06   44
    2  2011-11-07   45
    3  2011-11-08   45
    4  2011-11-09   45
    5  2011-11-10   45
    6  2011-11-11   45
    7  2011-11-12   45
    8  2011-11-13   45
    9  2011-11-14   46
    10 2011-11-15   46
    

    Although it is unclear from your question exactly what you want to do, a way to match this vector of dates (well, my data frame dat above) is via merge(). Say we have a vector of weeks we want to match against and some associated data in data frame weekdat:

    weekdat <- data.frame(Week = 44:50, Price = c(10, 20, 25, 30, 20, 15, 10))
    

    Then we can link dat with weekdat using merge() as so:

    > merge(dat, weekdat)
       Week      Dates Price
    1    44 2011-11-06    10
    2    45 2011-11-07    20
    3    45 2011-11-08    20
    4    45 2011-11-09    20
    5    45 2011-11-10    20
    6    45 2011-11-11    20
    7    45 2011-11-12    20
    8    45 2011-11-13    20
    9    46 2011-11-14    25
    10   46 2011-11-15    25
    11   46 2011-11-16    25
    12   46 2011-11-17    25
    13   46 2011-11-18    25
    14   46 2011-11-19    25
    15   46 2011-11-20    25
    16   47 2011-11-21    30
    17   47 2011-11-22    30
    18   47 2011-11-23    30
    19   47 2011-11-24    30
    20   47 2011-11-25    30
    21   47 2011-11-26    30
    22   47 2011-11-27    30
    23   48 2011-11-28    20
    24   48 2011-11-29    20
    25   48 2011-11-30    20
    26   48 2011-12-01    20
    

    There are other ways of matching or linking dates to weeks, but the above should give you something to work from.

提交回复
热议问题