r - 将年份添加到只有月和日的时间序列
问题描述
我有一个这样的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")
但是我又不知道如何为一年争论
请任何帮助都会为我节省很多时间,因为手动操作似乎是不可能的
解决方案
我们可以使用来自 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
推荐阅读
- javascript - 在 javascript 中使用 SetTimeOut 运行更新 UI 的函数时浏览器冻结
- laravel - Laravel groupBy 分页
- css - 在 Chrome DevTools 中有没有办法查看所有页面颜色?
- python - Openedx - 在创建课程时添加 Mongo 定义字段
- javascript - 为什么我不能通过点符号访问我的对象属性?
- javascript - 渐进式网络应用程序可以访问android文件系统吗
- javascript - 如何在 initialState 中为组织分配实际的对象数组而不是 promise?
- mysql - 如何解决 vb.net mysql 中出现的错误信息?
- c# - Core 3.1 DI Generic ApiController + 注入 Logger
- javascript - 无法将 activeClassName 或 activeStyle 添加到我的 react Navlinks React Router DOM