简体   繁体   中英

Add beginning-end ISO Week of ISO Year label

Consider the following:

df <- structure(list(date = structure(c(17542, 17543, 17544, 17545, 
                                        17546, 17547, 17548, 17549, 17550, 17551, 17552, 17553, 17554, 
                                        17555, 17556, 17557, 17558, 17559, 17560, 17561, 17562, 17563, 
                                        17564, 17565, 17566, 17567, 17568, 17569), class = "Date"), 
                     col1 = c(432L, 337L, 188L, 438L, 243L, 391L, 286L, 374L, 470L, 5L, 348L, 359L, 
                              435L, 221L, 271L, 311L, 143L, 169L, 119L, 438L, 75L, 248L, 19L, 284L, 
                              445L, 48L, 275L, 11L), 
                     col2 = c(282L, 483L, 195L, 140L, 458L, 433L, 435L, 218L, 49L, 169L, 298L, 269L, 
                              472L, 253L, 123L, 475L, 158L, 358L, 375L, 233L, 299L, 369L, 88L, 247L, 
                              6L, 392L, 170L, 6L), 
                     week = c(2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 
                              4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6)), 
                .Names = c("date", "col1", "col2", "week"))
df <- as.data.frame(df)
> df
         date col1 col2 week
1  2018-01-11  432  282    2
2  2018-01-12  337  483    2
3  2018-01-13  188  195    2
4  2018-01-14  438  140    2
5  2018-01-15  243  458    3
6  2018-01-16  391  433    3
7  2018-01-17  286  435    3
8  2018-01-18  374  218    3
9  2018-01-19  470   49    3
10 2018-01-20    5  169    3
11 2018-01-21  348  298    3
12 2018-01-22  359  269    4
13 2018-01-23  435  472    4
14 2018-01-24  221  253    4
15 2018-01-25  271  123    4
16 2018-01-26  311  475    4
17 2018-01-27  143  158    4
18 2018-01-28  169  358    4
19 2018-01-29  119  375    5
20 2018-01-30  438  233    5
21 2018-01-31   75  299    5
22 2018-02-01  248  369    5
23 2018-02-02   19   88    5
24 2018-02-03  284  247    5
25 2018-02-04  445    6    5
26 2018-02-05   48  392    6
27 2018-02-06  275  170    6
28 2018-02-07   11    6    6

I would like a column which spits out a string consisting of the ISO Week of the ISO Year. For example, when week is 2 , it should spit out Jan 8, 2018 to Jan 14, 2018 .

How does one do this? I would particularly appreciate a solution using lubridate , but am open to using other packages if needed.

Since you want to use lubridate , the following will give you a start:

library(lubridate)

df %>% mutate(week_start = floor_date(date, "week"), 
              week_end = ceiling_date(date, "week"))

I leave the problem of formatting and concatenating those boundary dates into the strings you want as a useful learning exercise for lubridate .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM