8

This has been frustrating me. Even with lubridate I can't get dates to maintain their type when I loop over them. For example:

require(lubridate)
yearrange = ymd(20110101) + years(seq(4))
yearrange
#[1] "2012-01-01 UTC" "2013-01-01 UTC" "2014-01-01 UTC" "2015-01-01 UTC"
class(yearrange)
#[1] "POSIXct" "POSIXt" 

However, if I try to loop through years (creating a separate plot for each year in my data set): I lose the formatting of the year, and would have to re-cast the data

for (yr in yearrange) { show(yr) }
#[1] 1325376000
#[1] 1356998400
#[1] 1388534400
#[1] 1420070400

If I loop though specifying indices, I get date objects back:

for (i in seq(length(yearrange))) { show(yearrange[i]) }
#[1] "2012-01-01 UTC"
#[1] "2013-01-01 UTC"
#[1] "2014-01-01 UTC"
#[1] "2015-01-01 UTC"

Is there an easy way to avoid the indexed option, without using foreach, or is that the only way?

thelatemail
  • 91,185
  • 12
  • 128
  • 188
beroe
  • 11,784
  • 5
  • 34
  • 79

2 Answers2

8

Try this

for (yr in as.list(yearrange))  { show(yr) }

I think for (yr in yearrange) coerces yearrange into a vector and POSIXct is not one of the supported types that vector coerces into.

cryo111
  • 4,444
  • 1
  • 15
  • 37
  • Thanks. This solves my problem. I am also going to implement it as a function instead of a `for` loop, so will probably take advantage of @thelatemail solution too – beroe Apr 29 '15 at 23:51
2

lapply doesn't seem to have the same problem, e.g.:

for (x in yearrange) plot(1, main=x)
#Main title = 1420070400
lapply( yearrange, function(x) plot(1, main=x) )
#Main title = 2015-01-01
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • 2
    Yes, because it uses `as.list(X)`, where `X=yearrange`. You can see it when you inspect the source code of `lapply`. – cryo111 Apr 29 '15 at 23:47
  • I'm going to make a function to generate my plots instead of looping so will use your answer as well, although the other one more directly solved my frustration. Thanks. – beroe Apr 29 '15 at 23:51