Question

In my dataset I have a column with the date and a column with the time:

YYMMDD   TIME
19861226  74751.00
19871214 204951.05
19891201 200914.35
19910215  21116.54
19910425 102631.58
19910808  40114.65

When I want to bind these two into one variable with df$datetime <- as.POSIXct(paste(df$YYMMDD,df$TIME),format='%Y%m%d %H%M%S'), I get NA values for the 1st, 4th and 6th row. This is probably due to the missing zero's. The original excel-file did include the zero's.

How do I solve this?

Was it helpful?

Solution

Use sprintf to format with leading zeroes:

sprintf("%09.2f",df$TIME)
[1] "074751.00" "204951.05" "200914.35" "021116.54" "102631.58" "040114.65"

so:

 df$datetime <- as.POSIXct(paste(df$YYMMDD,sprintf("%09.2f",df$TIME)),format='%Y%m%d %H%M%S')
 df
    YYMMDD      TIME            datetime
2 19861226  74751.00 1986-12-26 07:47:51
3 19871214 204951.05 1987-12-14 20:49:51
4 19891201 200914.35 1989-12-01 20:09:14
5 19910215  21116.54 1991-02-15 02:11:16
6 19910425 102631.58 1991-04-25 10:26:31
7 19910808  40114.65 1991-08-08 04:01:14
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top