8

I have list of dates having POSIXct class as follows (just a minimum working example):

L <- list(as.POSIXct("2012-12-12 12:12:12"), as.POSIXct("2012-12-12 12:12:12"))

I need to retrieve a vector of class POSIXct from it. This rules out lapply, and leaves me with sapply and vapply. I apply them as follows:

sapply(L, "[[", 1)

and this returns:

[1] 1355310732 1355310732

Converting this vector to POSIXct gives error as origin must be provided. I also tried vapply:

vapply(L, "[[", as.POSIXct(Sys.time()), 1)

but also get numeric vector returned:

[1] 1355310732 1355310732

Also unlist does not produce the desired POSIXct vector:

> unlist(L)
[1] 1355310732 1355310732 

In short, how do I extract a list of POSIXct values into a POSIXct vector?

Dmitrii I.
  • 696
  • 7
  • 16

1 Answers1

12

What about do.call?

L <- list(as.POSIXct("2012-12-12 12:12:12"), as.POSIXct("2012-12-12 12:12:12"))
do.call(c, L) # Execute function c on a list L of arguments.
[1] "2012-12-12 12:12:12 CET" "2012-12-12 12:12:12 CET"
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
plannapus
  • 18,529
  • 4
  • 72
  • 94
  • 1
    Indeed, as the manual on c function says: "All arguments are coerced to a common type...". Thanks. – Dmitrii I. Dec 13 '12 at 13:38
  • 3
    This may change the time zone though if the original list had a tz attribute.`L <- list(as.POSIXct("2012-12-12 12:12:12", tz = "UTC"), as.POSIXct("2012-12-12 12:12:12", tz = "GMT"))` which is easy to fix if all the tz values are the same, e.g. by `.POSIXct(do.call(c, L), tz = "UTC")` but how can you keep the time zones if they are different? – sparrow Dec 22 '14 at 23:58
  • @divibisan “`c` preserves attributes (like `class`)” — No, it does exactly the opposite, it *discards* them (and this is explicitly documented). But `POSIXct` provides its own `c` method to circumvent this. I’ve therefore rolled back your edit. – Konrad Rudolph Mar 22 '19 at 17:22
  • @KonradRudolph Ah, I see that. Thanks, I'm really glad you caught that! – divibisan Mar 22 '19 at 17:31
  • @divibisan Also, I apologise for my heavy-handed rollback. What you added did have value apart from the error. However, I’d actually suggest adding your own answer instead. – Konrad Rudolph Mar 22 '19 at 17:33
  • @KonradRudolph Don't worry about it! The fact that errors get smacked down is something I like about SO. I considered making an answer, but I don't have another approach to suggest, just a bit for additional info on the `do.call(c, L)` solution. That seems more worthy of an edit than a new question to me, though I'd be happy to hear otherwise from someone with more experience here. – divibisan Mar 22 '19 at 18:08