GabyLP
GabyLP

Reputation: 3781

r ifelse date not adding days

I need to compute a condition over a column date in R. Atable would be:

PIL_final1<-data.frame( prior_day1_cart=c(4,8),
                       prior_day1_comp=c('2014-06-03','2014-06-07'),
                       dia_lim_23_cart=c('201-07-30','201-07-30') )


PIL_final1$prior_day1_comp<-as.Date(PIL_final1$prior_day1_comp, format='%Y-%m-%d')
PIL_final1$dia_lim_23_cart<-as.Date(PIL_final1$dia_lim_23_cart, format='%Y-%m-%d')

So I use ifelse:

PIL_final1$llamar_dia<-ifelse(PIL_final1$prior_day1_cart+6>23, 
                             PIL_final1$dia_lim_23_cart , 
                            PIL_final1$prior_day1_comp+6)

But I get:

> PIL_final1
  prior_day1_cart prior_day1_comp dia_lim_23_cart llamar_dia
1               4      2014-06-03      0201-07-30      16230
2               8      2014-06-07      0201-07-30      16234

And if I do:

> PIL_final1$prior_day1_comp+6

[1] "2014-06-09" "2014-06-13"

I get the right results.

How can I do the ifelse and get the date? thanks.

Also if I try this, I still get a number (although different):

> PIL_final1$llamar_dia<-ifelse(PIL_final1$prior_day1_cart+6>23, 
+                              PIL_final1$dia_lim_23_cart , 
+                              as.Date(PIL_final$prior_day1_comp+6,format="%Y-%m-%d"))
> PIL_final1
  prior_day1_cart prior_day1_comp dia_lim_23_cart llamar_dia
1               4      2014-06-03      0201-07-30      16376
2               8      2014-06-07      0201-07-30      16377

Edition:

Also if I do this:

> as.Date(ifelse(PIL_final1$prior_day1_cart+6>23, PIL_final1$dia_lim_23_cart , 
+                PIL_final1$prior_day1_comp+6), format="%Y-%m-%d", origin="1970-01-01")

[1] "2014-06-09" "2014-06-13"

I get the right results, but if I replace the ifelse with the vector result, I get the wrong dates:

> PIL_final1$llamar_dia<-ifelse(PIL_final1$prior_day1_cart+6>23, 
+                              PIL_final1$dia_lim_23_cart , 
+                              PIL_final$prior_day1_comp+6)


 > as.Date(PIL_final1$llamar_dia, format="%Y-%m-%d", origin="1970-01-01")
[1] "2014-11-02" "2014-11-03"

Upvotes: 3

Views: 499

Answers (1)

agstudy
agstudy

Reputation: 121568

from ?ifelse :

The mode of the result may depend on the value of test (see the examples), Sometimes it is better >to use a construction such as

ifelse(test, yes, no) ~~ (tmp <- yes; tmp[!test] <- no[!test]; tmp)

Applying this :

dat$d3 <- 
with(dat,{
 tmp <- d2+6; tmp[!(x+6>23)] <- d1[!(x+6>23)]; tmp
})

dat
  x         d1         d2         d3
1 4 2014-06-03 0201-07-30 2014-06-03
2 8 2014-06-07 0201-07-30 2014-06-07

Maybe you should modify this to handle missing values in test.

Note I changed the variables names since yours are really long to type and a real source of errors.

dat <- data.frame( x=c(4,8),
                 d1=c('2014-06-03','2014-06-07'),
                 d2=c('201-07-30','201-07-30') )

Upvotes: 3

Related Questions