Oh Linh
Oh Linh

Reputation: 1

convert number to datetime in R

I have a dataframe with 2 columns. I want format column hhmm to %H:%M but the code does not work:

DF$hhmm <-as.POSIXct(strptime(DF$hhmm, "%H%M"))

I also want to merge the 2 columns into 1 column DateTime like 2002-07-08 22:00

YYYY-MM-DD  hhmm
2002-07-08  2200    
2002-07-08  2300    
2002-07-09  0   
2002-07-09  100 
2002-07-09  200 
2002-07-09  300 
2002-07-09  400

Upvotes: 0

Views: 640

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99371

You could bring the columns together first with sprintf(), then use as.POSIXct().

x <- with(df, sprintf("%s %04d", YYYY.MM.DD, hhmm))
data.frame(DateTime = as.POSIXct(x, format = "%Y-%m-%d %H%M"))
#              DateTime
# 1 2002-07-08 22:00:00
# 2 2002-07-08 23:00:00
# 3 2002-07-09 00:00:00
# 4 2002-07-09 01:00:00
# 5 2002-07-09 02:00:00
# 6 2002-07-09 03:00:00
# 7 2002-07-09 04:00:00

where df is

df <- structure(list(YYYY.MM.DD = structure(c(1L, 1L, 2L, 2L, 2L, 2L, 
2L), .Label = c("2002-07-08", "2002-07-09"), class = "factor"), 
hhmm = c(2200L, 2300L, 0L, 100L, 200L, 300L, 400L)), .Names = c("YYYY.MM.DD", 
"hhmm"), class = "data.frame", row.names = c(NA, -7L))

Upvotes: 1

Related Questions