Reputation: 3280
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??
Upvotes: 1
Views: 194
Reputation: 269471
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)
Upvotes: 1
Reputation: 121568
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
Upvotes: 1
Reputation: 13046
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")
Upvotes: 2
Reputation: 206187
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.
Upvotes: 1