首页 > 解决方案 > 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

你有什么想法可以帮助我吗?

标签: rdatelubridatebase

解决方案


您可以使用parse_date_time以不同格式更改日期和时间来POSIXct上课。如果出生年份小于 1910,则将birthvalue替换为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))

推荐阅读