r - Posixct 日期的条件
问题描述
我有一个异构数据,比如日期是 POISXct 格式
ID birth new_birth
1 1990-10-16 NA
2 1883-12-31 23:50:39 1983-12-31
3 1945-01-16 00:00:00 NA
如果 new_birth 和birth<1910 中有内容,我想替换birth 我在日期时间更改birth 和new_birth 为as.Date 我想创建新列Year
df <- df %>%
mutate(Year = as.date(birth, format="Y")
但是年份停留在 YMD 格式,为什么?在我想做 ifelse 之后终于有了
ID birth new_birth
1 1990-10-16 NA
2 1983-12-31 1983-12-31
3 1945-01-16 NA
你有什么想法可以帮助我吗?
解决方案
您可以使用parse_date_time
以不同格式更改日期和时间来POSIXct
上课。如果出生年份小于 1910,则将birth
value替换为new_birth
。
library(dplyr)
library(lubridate)
df %>%
mutate(birth = as.Date(parse_date_time(birth, c('Ymd', 'YmdHMS'))),
new_birth = as.Date(new_birth),
birth = if_else(year(birth) < 1910, new_birth, birth))
# ID birth new_birth
#1 1 1990-10-16 <NA>
#2 2 1983-12-31 1983-12-31
#3 3 1945-01-16 <NA>
数据
df <- structure(list(ID = 1:3, birth = c("1990-10-16", "1883-12-31 23:50:39",
"1945-01-16 00:00:00"), new_birth = c(NA, "1983-12-31", NA)),
class = "data.frame", row.names = c(NA, -3L))
推荐阅读
- amazon-web-services - AWS 预测 - 参数“回测窗口”的真正含义是什么?
- sql - 为什么在我使用 ISNUMERIC() 时强制转换失败?
- ios - 为什么我在运行 Pod install 时会收到此错误“[!] An error occurred while processing the post-install hook of the Podfile.”
- javascript - 为什么 foo 函数内外的参数值不同
- javascript - 从孩子那里获取信息给父母
- laravel - 如何重定向到分页中的“帖子”
- python - Python Pandas 嵌套 JSON
- r - 如何从 glmnet 多项式中恢复非零系数?
- java - Java Maven 程序集插件 - 多个主文件
- vue.js - 使用 GitLab Pipeline 将 Vue Js Webapp 上传到 VMware 会出现 403 禁止错误