Question

I am trying to locate the nearest Sunday to today.

I define today as:

dt <- as.Date("2014-06-04")

I can find the last Sunday by following:

dt - as.POSIXlt(dt)$wday
[1] "2014-06-01"

I can find the next Sunday by following:

dt + as.POSIXlt(dt)$wday
[1] "2014-06-07"

Not sure why the following is not working:

ifelse(as.POSIXlt(dt)$wday <= 3, 
       dt - as.POSIXlt(dt)$wday, 
       dt + as.POSIXlt(dt)$wday)
[1] 16222

I am getting a number: 16222 instead of a date.

Each of the following statements work as expected:

as.POSIXlt(dt)$wday
class(as.POSIXlt(dt)$wday)
as.POSIXlt(dt)$wday <= 3

Any ideas??

Was it helpful?

Solution

It appears that ifelse returns a vector and strips the "POSIX" class from your dates. Why not do

dt + ifelse(as.POSIXlt(dt)$wday <= 3, -1, 1) * as.POSIXlt(dt)$wday

instead.

OTHER TIPS

Another solution: restore the class attribute by calling e.g.:

structure(ifelse(as.POSIXlt(dt)$wday <= 3, 
       dt - as.POSIXlt(dt)$wday, 
       dt + as.POSIXlt(dt)$wday), class="Date")

No need to use an ifelse here, A classic if/else will do the job:

if(as.POSIXlt(dt)$wday <= 3) dt - as.POSIXlt(dt)$wday else dt + as.POSIXlt(dt)$wday
[1] "2014-06-01"

Or even simpler:

wday <- as.POSIXlt(dt)$wday 
dt + if(wday<= 3) -wday else wday

1) Try this:

wday <- as.POSIXlt(dt)$wday
dt + ifelse(wday <= 3, -wday, 7-wday)

This applies the ifelse to the number of days added or subtracted. ifelse works well with plain numbers but not with complex types like "Date" class so this avoids the application of ifelse to "Date" class objects.

Note that if wday > 3 then we want to add 7-wday and not wday (as in the question).

The solution here continues to work even if dt is a vector of dates.

2) Note that the second line of the answer in (1) could alternately be written the following way which first computes the last Sunday (dt-wday) and adds 7 to get the next Sunday if its past Wednesday in the week.

dt - wday + ifelse(wday > 3, 7, 0)

3) Yet another way to express this is:

dt - wday + 7 * (wday > 3)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top