有没有办法用lubridate软件包找到x年x周的第一天?
例如,我有这样的数据:某一年的周数(例如,1988年的第33周(,我想将其转换为这样的数据,如:天/月/年(例如1988年8月15日(。
Missing_day <- c("33/1988", "37/1991", "37/1992",
"41/1994", "15/1997", "18/2001",
"50/2001", "16/2002", "35/2004",
"5/2012", "50/2012", "8/2013",
"36/2013", "51/2017")
感谢
您可以附加工作日并将数据转换为Date。使用基本R,你可以做:
as.Date(paste0('1/', Missing_day), '%u/%U/%Y')
# [1] "1988-08-15" "1991-09-16" "1992-09-14" "1994-10-10" "1997-04-14"
# [6] "2001-05-07" "2001-12-17" "2002-04-22" "2004-08-30" "2012-01-30"
#[11] "2012-12-10" "2013-02-25" "2013-09-09" "2017-12-18"
请注意此处关于的讨论
- 指定星期几
- 确保您了解R列举一年中几周的不同方式
library(dplyr)
library(stringr)
# Using Lubridate per your request
library(lubridate)
tibble(week_year = Missing_day) %>%
mutate(
day_month_year = format(lubridate::parse_date_time(
paste(
str_extract(string = week_year, pattern = "^\d+"),
str_extract(string = week_year, pattern = "\d*$"),
'Mon',
sep =
"/"
), 'W/Y/a'
), "%d/%m/%Y")
)
# A tibble: 14 x 2
# week_year day_month_year
# <chr> <chr>
# 1 33/1988 15/08/1988
# 2 37/1991 16/09/1991
# 3 37/1992 14/09/1992
# 4 41/1994 10/10/1994
# 5 15/1997 14/04/1997
# 6 18/2001 30/04/2001
# 7 50/2001 10/12/2001
# 8 16/2002 22/04/2002
# 9 35/2004 30/08/2004
# 10 5/2012 30/01/2012
# 11 50/2012 10/12/2012
# 12 8/2013 25/02/2013
# 13 36/2013 09/09/2013
# 14 51/2017 18/12/2017
# Using Base R
tibble(week_year = Missing_day) %>%
mutate(
day_month_year = format(as.Date(
paste(
1,
str_extract(string = week_year, pattern = "^\d+"),
str_extract(string = week_year, pattern = "\d*$"),
sep = "/"
), "%w/%W/%Y"
), "%d/%m/%Y")
)
# A tibble: 14 x 2
# week_year day_month_year
# <chr> <chr>
# 1 33/1988 15/08/1988
# 2 37/1991 16/09/1991
# 3 37/1992 14/09/1992
# 4 41/1994 10/10/1994
# 5 15/1997 14/04/1997
# 6 18/2001 30/04/2001
# 7 50/2001 10/12/2001
# 8 16/2002 22/04/2002
# 9 35/2004 30/08/2004
# 10 5/2012 30/01/2012
# 11 50/2012 10/12/2012
# 12 8/2013 25/02/2013
# 13 36/2013 09/09/2013
# 14 51/2017 18/12/2017