首页 > 解决方案 > 将年份添加到只有月和日的时间序列

问题描述

我有一个这样的df

    month   day   x
1   1        1    84
2   1        2    43
3   1        3    49
4   1        4    67
5   1        5    59
......
366 12       31   97

从 10 月到 12 月应该是 2019 年,从 1 月到 9 月应该是 2020 年

我试着用

df$year<-as.date(df,origin='2019-01-01')

但我不确定如何提出论点。

我希望年份列获取日期列,然后尝试

df$date<-as.date(with(paste("???",month,day,sep="-"), %Y-%m-%d,origin ="2019-01-01")

但是我又不知道如何为一年争论

请任何帮助都会为我节省很多时间,因为手动操作似乎是不可能的

标签: rtimetime-series

解决方案


我们可以使用来自 lubridateifelse的函数的语句:make_date

library(dplyr)
library(lubridate)
df %>% 
  mutate(year= ifelse(month %in% c(10,11,12), 2019, 2020),
         date = make_date(year, month, day))

输出:

    month day  x year       date
1       1   1 84 2020 2020-01-01
2       1   2 43 2020 2020-01-02
3      11   3 49 2019 2019-11-03
4       1   4 67 2020 2020-01-04
5       1   5 59 2020 2020-01-05
366    12  31 97 2019 2019-12-31

推荐阅读