Posixct 日期的条件

condition on Posixct date

我有一个异构数据,比如 日期采用 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 我用 as.Date 更改日期时间中的出生 & new_birth 我想创建和新列 Year with

df <- df %>% 
 mutate(Year = as.date(birth, format="Y")  

但是 Year 保持格式 YMD,为什么? 在我想做 ifelse 之后 finally

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 class。如果出生年份小于 1910,则将 birth 值替换为 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))

我们可以使用 coalesce 以更简单的方式完成此操作 - 将 'birth' 列中的不同日期时间格式与 anydate and coalesce 列一起转换

library(dplyr)
library(anytime)
df %>%
    mutate(across(-ID, anydate), birth = coalesce(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))