如何使用 R 中的 lubridate 将周和年列转换为日期列
How to convert week and year columns to a date column with lubridate in R
我一直在关注 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
如果需要,您可以使用 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
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))
我一直在关注 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
如果需要,您可以使用 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
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))