我一直在关注 Hadley Wickham 的《R for data science》一书。他对使用 lubridate 有很多建议,但很多函数都假设您有年、月和日。当您只有年和周时,如何使用 lubridate 转换为日期格式?
data.frame(
year = c(2015, 2015, 2016, 2016, 2016, 2016, 2016),
week = c(1, 20, 35, 49, 8, 4, 53)
)
#year week
#2015 1
#2015 20
#2016 35
#2016 49
#2016 8
#2016 4
#2016 53
Run Code Online (Sandbox Code Playgroud)
weeks()如果需要,您可以使用 lubridate 中的函数来完成此操作。您只需首先设置一个基准日期对象。我在这里使用str_cfrom stringr 做到了这一点。
library(dplyr)
library(stringr)
my_dates <- tribble(
~year, ~week,
2015, 1,
2015, 20,
2016, 35,
2016, 49,
2016, 8,
2016, 4,
2016, 53
)
my_dates %>%
mutate(beginning = ymd(str_c(year, "-01-01")),
final_date = beginning + weeks(week))
#> # A tibble: 7 x 4
#> year week beginning final_date
#> <dbl> <dbl> <date> <date>
#> 1 2015 1 2015-01-01 2015-01-08
#> 2 2015 20 2015-01-01 2015-05-21
#> 3 2016 35 2016-01-01 2016-09-02
#> 4 2016 49 2016-01-01 2016-12-09
#> 5 2016 8 2016-01-01 2016-02-26
#> 6 2016 4 2016-01-01 2016-01-29
#> 7 2016 53 2016-01-01 2017-01-06
Run Code Online (Sandbox Code Playgroud)