ngn16920
ngn16920

Reputation: 77

R: Unambiguous format when reading zoo and converting to with "as.POSIXct"

I am trying to read some data into a read.zoo data, but always getting some error:

Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

The code is:

df_zoo <- read.zoo("mydata.csv",
                header = TRUE,
                sep = ";",
                index = 1:2,
                FUN = paste,
                FUN2 = as.POSIXct,
                format = "%d.%m.%Y %H:%M:%S",
                tz = "UTC",
                dec = ",")

The first lines of the log are

DATE;TIME_UTC;#1;#2;#3
14.06.2016;12:15:11;TRUE;TRUE;43,2
14.06.2016;12:15:12;TRUE;TRUE;43,3
14.06.2016;12:15:13;TRUE;TRUE;43,3
...

I could change the date in the CSV, but it should be doable in R and i don't want to change it for any further CSV. Also

as.POSIXct(paste("14.06.2016","12:15:11"), format = "%d.%m.%Y %H:%M:%S", tz = "UTC")

is working just fine:

[1] "2016-06-14 12:15:11 UTC"

I don't see the problem.

Upvotes: 1

Views: 821

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269664

1) read.zoo will automatically paste multi-column indexes together so this will work and does not use FUN= at all. Note that zoo represents the data as a matrix and so in this case the logicals will be coerced to numeric.

library(zoo)
read.zoo("mydata.csv", check.names = FALSE,
  header = TRUE, sep = ";", comment = "", dec = ",",
  index = 1:2, format = "%d.%m.%Y %H:%M:%S", tz = "")

2) read.zoo can also read data frames so this would work and takes advantage of the fact that many of the needed arguments are default arguments of read.csv2:

d <- read.csv2("mydata.csv", check.names = FALSE)
read.zoo(d, index = 1:2, format = "%d.%m.%Y %H:%M:%S", tz = "")

Upvotes: 1

hvollmeier
hvollmeier

Reputation: 2986

You only need 1 FUN line to define the function to paste col1 and col2:

FUN = function(d,t) as.POSIXct(paste(d,t),format = "%d.%m.%Y %H:%M:%S",tz = "UTC”)

So to import your file as zoo object:

df_zoo <- read.zoo("mydata.csv",
                header = TRUE,
                sep = ";",
                index = 1:2,
                FUN = function(d,t) as.POSIXct(paste(d,t),format = "%d.%m.%Y %H:%M:%S",tz = "UTC"),
                dec = ",")

Upvotes: 0

Related Questions