NANA
NANA

Reputation: 13

lubridate :: interval() returns numeric values once in a for loop

I have code that worked last week and is not working this week. I'm using lubridate::interval(), which works perfectly well for the below data outside of a for loop, but as soon as I put it inside a for loop it returns numeric values rather than intervals.

# sample code
    sunset <- as.POSIXct(c("2019-11-05 19:12:17", "2019-11-06 19:13:04", "2019-11-07 19:13:51"), 
                     tz = "Pacific/Norfolk") 

sunrise <- as.POSIXct(c("2019-11-06 05:53:04", "2019-11-07 05:52:23", "2019-11-08 05:51:43"), 
                      tz = "Pacific/Norfolk")
# sample data frame

ds <- data.frame( "sunset" = sunset, 
                 "sunrise" = sunrise)

interval(start = ds$sunset[1],  # check the interval function is working
         end = ds$sunrise[1])

which returns:

[1] 2019-11-05 19:12:17 +12--2019-11-06 05:53:04 +12

but inside a for loop:

for (i in seq_along(ds$sunset)) {
  
  ds$interval[i] <- interval(start = ds$sunset[i],
                                   end = ds$sunrise[i])
}

it returns:

> ds
               sunset             sunrise interval
1 2019-11-05 19:12:17 2019-11-06 05:53:04    38447
2 2019-11-06 19:13:04 2019-11-07 05:52:23    38359
3 2019-11-07 19:13:51 2019-11-08 05:51:43    38272

I've tried wrapping the interval() section in as.interval() but that just returned numeric values again. I'd appreciate any help with this. Thanks :)

Upvotes: 1

Views: 212

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24790

The problem you're having is that you need to pre-initialize the column of ds as class interval:

library(lubridate)

ds$interval <- rep(interval(as.POSIXct(NA,tz = "Pacific/Norfolk"),
                   as.POSIXct(NA,tz = "Pacific/Norfolk")),
                   3)

for (i in seq_along(ds$sunset)) {  
  ds$interval[i] <- interval(start = ds$sunset[i],
                                   end = ds$sunrise[i])
}
ds
#               sunset             sunrise                                         interval
#1 2019-11-05 19:12:17 2019-11-06 05:53:04 2019-11-05 07:12:17 UTC--2019-11-05 17:53:04 UTC
#2 2019-11-06 19:13:04 2019-11-07 05:52:23 2019-11-06 07:13:04 UTC--2019-11-06 17:52:23 UTC
#3 2019-11-07 19:13:51 2019-11-08 05:51:43 2019-11-07 07:13:51 UTC--2019-11-07 17:51:43 UTC

Upvotes: 2

Related Questions