Reputation: 1441
I'm reading a csv file of precipitation time series, the problem is when the time is 00:00
.
head(C1)
fecha precip
1 09/04/2012 0
2 09/04/2012 0:05 0
3 09/04/2012 0:10 0
4 09/04/2012 0:20 0
5 09/04/2012 0:25 0
6 09/04/2012 0:30 0
I'm trying to obtain a zoo object, but if I change time to POSIXct, or POSIXlt:
C1$fecha <- as.POSIXct(C1$fecha, format="%d/%m/%Y %k:%M")
I get NA on problematic dates.
head(C1)
fecha precip
1 <NA> 0
2 2012-04-09 00:05:00 0
3 2012-04-09 00:10:00 0
4 2012-04-09 00:20:00 0
5 2012-04-09 00:25:00 0
6 2012-04-09 00:30:00 0
Any hint on this? Thanks
Upvotes: 2
Views: 170
Reputation: 269664
If x
is your vector of dates and date/times then try this:
as.POSIXct(paste(x, "00:00"), format = "%m/%d/%Y %k:%M")
Upvotes: 0
Reputation: 179438
One solution is to find the strings that are short, i.e. don't have time information. Then concatenate 0:00
to each of these strings before converting to datetime objects:
Create sample data:
x <- c("09/04/2012", "09/04/2012 0:05", "09/04/2012 0:10", "09/04/2012 0:20",
"09/04/2012 0:25", "09/04/2012 0:30")
Use nchar()
to identify elements that are only 10 characters in length. Then paste()
0:00
to these elements:
index <- sapply(x, nchar) == 10
x[index] <- paste0(x[index], " 0:00")
as.POSIXct(x, format="%d/%m/%Y %k:%M")
[1] "2012-04-09 00:00:00 BST" "2012-04-09 00:05:00 BST" "2012-04-09 00:10:00 BST"
[4] "2012-04-09 00:20:00 BST" "2012-04-09 00:25:00 BST" "2012-04-09 00:30:00 BST"
Upvotes: 3