【问题标题】:using ifelse with Dates in R在 R 中使用带有日期的 ifelse
【发布时间】:2026-01-25 19:35:01
【问题描述】:

我有一个日期向量,如果它在另一个向量之前,我想将日期设置为 NA。

我试过ifelse(date_vector1>=date_vector2, date_vector1, NA),但输出不是日期,应用as.Date()返回错误。

然后我尝试了dplyr::if_else(date_vector1>=date_vector2, date_vector1, NA_real_),但它返回了同样的错误。

错误是这个:

as.Date.numeric(value) 中的错误:必须提供“原点”

如何使用ifelse 声明日期?

【问题讨论】:

  • 请不要在约会时使用if_elseifelse。而是尝试setDT(df1)[date_vector>= date_vector2, newcol := date_vector1]

标签: r date


【解决方案1】:

我们可以使用data.table创建一个新列

library(data.table)
setDT(df1)[date_vector1>= date_vector2, newcol := date_vector1]
df1
#   date_vector1 date_vector2     newcol
#1:   2017-05-29   2017-05-13 2017-05-29  
#2:   2017-05-22   2017-05-26       <NA>
#3:   2017-05-26   2017-05-18 2017-05-26
#4:   2017-05-28   2017-05-14 2017-05-28
#5:   2017-05-25   2017-05-27       <NA>

如果这两个向量不是data.frame/data.table中的变量,那么做

i1 <- date_vector1>= date_vector2
newvector <- date_vector2
newvector[i1] <- date_vector1[i1]
newvector[!i1] <- NA
newvector
#[1] "2017-05-29" NA           "2017-05-26" "2017-05-28" NA    

最好不要在Date 上使用ifelse,因为日期存储为整数,它将强制转换为integer 类,我们可能必须再次使用as.Date(..., origin = '1970-01-01') 将其转换回Date

数据

set.seed(24)
date_vector1 <- sample((Sys.Date() - 1:10), 5, replace = FALSE)
date_vector2 <- sample((Sys.Date() - 1:20), 5, replace = FALSE)
df1 <- data.frame(date_vector1, date_vector2)

【讨论】:

  • 我最终选择了foo=date_vector1foo[date_vector1&gt;= date_vector2]=NA,但您的回答可能对其他情况非常有价值
【解决方案2】:

这是因为ifelse strips the class attribute。您可以使用例如恢复它

date_vector3 <- ifelse(date_vector1>=date_vector2, date_vector1, NA)
class(date_vector3) <- "Date"

【讨论】:

    【解决方案3】:

    当其中一种情况是固定值时,我通常会选择replace()

    date1 <- Sys.Date() + c(-1, 0, 1)
    date2 <- Sys.Date() + c(0, 0, 0)
    
    replace(date1, which(date1 < date2), NA)
    #> [1] NA           "2022-02-25" "2022-02-26"
    

    【讨论】: