2017-07-28 48 views
2

我一直在關注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 
+2

也許'有(DF1,as.Date(sprintf的( 「%d%02D 1」,一年,周), 「%Y%U%U」))' – akrun

+1

退房這個問題:HTTPS: //stackoverflow.com/questions/9380435/how-to-parse-year-week-number-in-r –

+0

@akrun is asdate with base or lubridate? – Alex

回答

3

如果需要,可以使用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 
+0

在此版本中,最後一項不是「NA」 ;它計算到下一年。 –

+0

爲什麼'asdate'在'ymd()'裏面?不是'ymd'照顧的嗎? – thelatemail

+0

啊,是的,哎呀!我編輯它。 –

2

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)) 
+0

作爲一個旁白,這是解決方案如果不是那些令人沮喪的閏年,那麼它會起作用:'mutate(date = as_date(((year - 1970)* 365)+(week * 7) - 1))' –

相關問題