在R中使用带日期的ifelse [英] using ifelse with Dates in R

查看:57
本文介绍了在R中使用带日期的ifelse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期向量,如果要早于另一个向量,我想将日期设置为NA.

我尝试了 ifelse(date_vector1> = date_vector2,date_vector1,NA),但是输出不是Date,并且应用了 as.Date()返回错误./p>

然后我尝试了 dplyr :: if_else(date_vector1> = date_vector2,date_vector1,NA_real _),但它返回了相同的错误.

错误是这个:

as.Date.numeric(value)中的错误:必须提供'origin'

如何在日期中使用 ifelse 语句?

解决方案

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

 库(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_vector2newvector<-date_vector2newvector [i1]<-date_vector1 [i1]newvector [!i1]<-NA新向量#[1]" 2017-05-29"NA"2017-05-26";" 2017-05-28"不适用 


最好不要在 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) 

I have a vector of dates and I want to set the date to NA if it is prior to another vector.

I tried ifelse(date_vector1>=date_vector2, date_vector1, NA), but the output is not a Date and applying as.Date() return an error.

I then tried dplyr::if_else(date_vector1>=date_vector2, date_vector1, NA_real_), but it returns the same error.

The error is this one :

Error in as.Date.numeric(value) : 'origin' must be supplied

How can I use the ifelse statement with dates ?

解决方案

We can use data.table to create a new column

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

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')

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)

这篇关于在R中使用带日期的ifelse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆