簡體   English   中英

如何在R中使用lubridate將周和年列轉換為日期列

[英]How to convert week and year columns to a date column with lubridate in R

我一直在關注Hadley Wickham的R for data science book。 他在使用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

如果需要,可以使用lubridate中的week weeks()函數來執行此操作。 您只需要首先設置一個基准日期對象。 我這樣做,在這里使用str_c從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

Arkun的回答很整潔而准確,但是既然您問起使用lubridate我想我會加2美分。 您要為相關年份定義元旦,然后從中提前指定的周數。 這樣就更容易解釋leap年了(這阻礙了我為回答這個問題所做的第一努力)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM