实际上,我已经转换了这样的数据
code name returns year week
1 A 0.66 2000 01
2 A 0.32 2000 02
3 A 0.66 2000 03
4 A 0.99 2000 04
5 A 0.55 2000 05
到看起来像这样的数据帧
code name returns date
1 A 0.66 07-01-2000
2 A 0.32 14-01-2000
3 A 0.66 21-01-2000
4 A 0.99 NA
5 A 0.55 05-02-2000
这是通过以下命令完成
的setDT(weekly)[,date:=as.Date(paste(year, week, 5, sep="-"), "%Y-%U-%u")]
但是,我不知道为什么上周,即第 52 周......缺少最后日期。
我想用之前的日期 + 7 天替换 NA。
输出应如下所示
code name returns date
1 A 0.66 07-01-2000
2 A 0.32 14-01-2000
3 A 0.66 21-01-2000
4 A 0.99 28-01-2000
5 A 0.55 05-02-2000
**Note- Here, year 2000 is just an example. Actually, NA occurs whenever month changes from Thursday.**
如果您总是在最后一个日期中添加 7 天,您可以尝试这样的事情:
library(tidyverse)
library(lubridate)
df %>%
mutate(new = as.Date.numeric(ifelse(is.na(date) == TRUE, lag(date) + days(7), date),
origin = "1970-01-01" ))
输出:
code name returns date new
1 1 A 0.66 2020-01-07 2020-01-07
2 2 A 0.32 2020-01-14 2020-01-14
3 3 A 0.66 2020-01-21 2020-01-21
4 4 A 0.99 <NA> 2020-01-28
5 5 A 0.55 2020-02-05 2020-02-05
示例数据:
df <- read.table(text = "code name returns date
1 A 0.66 07-01-2000
2 A 0.32 14-01-2000
3 A 0.66 21-01-2000
4 A 0.99 NA
5 A 0.55 05-02-2000
", header = TRUE) %>%
mutate(date = as.Date.character(date, tryFormats = c("%d-%m-%y")))