简体   繁体   English

在 R 中使用带有日期的 ifelse

[英]using ifelse with Dates in R

I have a vector of dates and I want to set the date to NA if it is prior to another vector.我有一个日期向量,如果它在另一个向量之前,我想将日期设置为 NA。

I tried ifelse(date_vector1>=date_vector2, date_vector1, NA) , but the output is not a Date and applying as.Date() return an error.我试过ifelse(date_vector1>=date_vector2, date_vector1, NA) ,但 output 不是 Date 并且应用as.Date()返回错误。

I then tried dplyr::if_else(date_vector1>=date_vector2, date_vector1, NA_real_) , but it returns the same error.然后我尝试dplyr::if_else(date_vector1>=date_vector2, date_vector1, NA_real_) ,但它返回相同的错误。

The error is this one:错误是这个:

Error in as.Date.numeric(value): 'origin' must be supplied as.Date.numeric(value) 中的错误:必须提供“原点”

How can I use the ifelse statement with dates?如何使用带有日期的ifelse语句?

We can use data.table to create a new column我们可以使用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>

If both these are vectors are not a variable in a data.frame/data.table, then do如果这两个都是向量而不是 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    

It is better not to use ifelse on Date as dates are stored as integers it will coerce to integer class and we may have to convert it back to Date class again with as.Date(..., origin = '1970-01-01')最好不要在Date上使用ifelse ,因为日期存储为整数,它将强制转换为integer as.Date(..., origin = '1970-01-01') ,我们可能必须将其转换回Date class 再次使用as.Date(..., origin = '1970-01-01')

data数据

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)

This because ifelse strips the class attribute .这是因为ifelse剥离了 class 属性 You can restore it with eg您可以使用例如恢复它

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

I normally go for replace() when one of the cases is a fixed value:当其中一种情况是固定值时,我通常使用 go 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM