如何将周列和年列转换为Rridridate中的日期列
我一直在关注Hadley Wickham的R for data science book。他对使用lubridate有很多建议,但很多功能都假设你有年,月,日。当你所有的年份和周使用lubridate时,你如何转换为日期格式?如何将周列和年列转换为Rridridate中的日期列
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
如果需要,可以使用lubridate中的weeks()
函数完成此操作。您只需首先设置基准日期对象。我在这里使用stringr的str_c
。
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
在此版本中,最后一项不是“NA” ;它计算到下一年。 –
为什么'asdate'在'ymd()'里面?不是'ymd'照顾的吗? – thelatemail
啊,是的,哎呀!我编辑它。 –
Arkun的回答是整洁和准确的,但既然你问有关使用lubridate
我想我会加入我的两分钱。您想定义有问题的每年的元旦,然后提前指定的周数。这使得闰年更容易计算(这阻碍了我第一次回答这个问题)。
library(tidyverse)
library(lubridate)
date_week <- data.frame(
year = c(2015, 2015, 2016, 2016, 2016, 2016, 2016, 1970),
week = c(1, 20, 35, 49, 8, 4, 53, 1)
)
date_week %>%
tbl_df() %>%
mutate(newyears = ymd(paste0(year,"-01-01"))) %>%
mutate(date = newyears + weeks(week))
作为一个旁白,这是解决方案如果不是那些令人沮丧的闰年,那么它会起作用:'mutate(date = as_date(((year - 1970)* 365)+(week * 7) - 1))' –
也许'有(DF1,as.Date(sprintf的( “%d%02D 1”,一年,周), “%Y%U%U”))' – akrun
退房这个问题:HTTPS: //stackoverflow.com/questions/9380435/how-to-parse-year-week-number-in-r –
@akrun is asdate with base or lubridate? – Alex