5

I have a list of strings that is in our date format and I want to convert it into a list of posix dates that I can manipulate with R, how can I do that?

This is what I have but I end up with a list of lists:

 a <- c("2009.01.01 00:00:00", "2009.01.01 00:00:00")

z <- lapply(a,function(x){strptime(x, "%Y.%m.%d %H:%M:%S")})

> z <- lapply(a,function(x){strptime(x, "%Y.%m.%d %H:%M:%S")})
> summary(z)
     Length Class   Mode
[1,] 1      POSIXlt list
[2,] 1      POSIXlt list
Berlin Brown
  • 11,504
  • 37
  • 135
  • 203
  • 1
    Note that `a` isn't a list, it's a vector (in R's terms). `strptime` is vectorized (see joran's answer), which means it works on all instances of that vector. If you indeed had a list, lapply would be appropriate. Also notice that `z` IS a list of vectors (and not a list of lists). – Roman Luštrik Jan 26 '12 at 18:28

2 Answers2

10

strptime is vectorized:

a <- c("2009.01.01 12:20:10", "2009.01.01 04:12:14")
> out <- strptime(a, "%Y.%m.%d %H:%M:%S")
> str(out)
 POSIXlt[1:2], format: "2009-01-01 12:20:10" "2009-01-01 04:12:14"
joran
  • 169,992
  • 32
  • 429
  • 468
0

you can use the c() function with:

do.call(c,z)

You can check the doc for more details.

ITChap
  • 4,057
  • 1
  • 21
  • 46
MCT
  • 1