[R] ifelse and dates do not work together: What workaround?

Farrel Buchinsky fjbuch at gmail.com
Thu Sep 27 22:09:30 CEST 2007


I encountered the above problem. I went to the help files and
discovered the reason why. My insight as to why it was happening did
not immediately provide me with a solution by which I could accomplish
what I needed to do. I turned to the help archive. I encountered a
thread on which somebody pointed this problem out and was mildly
castigated for not having looked at the help file. Alas no workaround
was provided.

ifelse(test, yes, no) is wonderful since it works well in a dataframe
but only if yes and no are something simple, such as a numeric vector.
But if yes and no are dates then it does not work.

My workaround was quite inelegant.
Instead of the elegance of
official.date<-ifelse(is.na(x),dateyes,dateno)

I resorted to conditional indexing.
official.date<-dateno #only apporopriate when x is not missing
official.date[is.na(x)]<-dateyes[is.na(x)]


Original thread:
On Sat, 3 Jun 2006, ivo welch wrote:

> I wonder if this is an intentional feature or an oversight.

These are documented properties of the functions you are using.

> in some column summaries or in ifelse operations, apparently I am losing
> the date property of my vector.
>
...
>> ifelse( is.na(c), e, c )
> [1] 4017 4048 4076   # date property is lost

As documented. From ?ifelse:

Value:

      A vector of the same length and attributes (including class) as
      'test' and data values from the values of 'yes' or 'no'.  The mode
      of the answer will be coerced from logical to accommodate first
      any values taken from 'yes' and then any values taken from 'no'.

Note that the class is taken from 'test'.

> PS: this time I do not need help.  I can write my code around this.

Help in pointing you to the posting guide and its recommended reading of
the help page might still be helpful.





-- 
Farrel Buchinsky
GrandCentral Tel: (412) 567-7870



More information about the R-help mailing list