0

I have a field in a R dataframe, say called OriginTime. The field has basically two types of values, read in from several excel files and rbinded together. Example df follows:

OriginTime <- c(0.777888, 0.999888, 0.25, 0.3755, "12:24", "05:59")

The entire column is character values. I want to convert the entire column to time field in the format hh:mm. But whenever I attempt to convert the column values, say using chron::times, the rows with an already hh:mm format get turned into NA values, and the decimal values are correctly reformated. I have attempted various methods to resolve but to no avail. One example

ifelse(substr(OriginTime,3,3)!=":",chron::times(as.numeric(as.character(OriginTime))),OriginTime)
guasi
  • 1,461
  • 3
  • 12
r_user
  • 1
  • 4

1 Answers1

0

It seems chron::times is very picky about the time format. It complains and says it's expecting 3 items "h:m:s" when converting "12:24".

The following solution transforms numeric values separately from character values of type "h:m:s" and then combines the result. I tried doing it on one pass with an if statement like you tried, but the resulting vector did not retain the time format.

v1 <- chron::times(as.numeric(OriginTime))
v2 <- chron::times(paste0(OriginTime,":00"))

fixed <- ifelse(is.na(v1), v2, v1)
fixed <- chron::times(fixed)

Edit: I realize you can do it on one pass with this

fixed2 <- sapply(OriginTime,
                \(x) ifelse(grepl(":",x),
                            chron::times(paste0(x,":00")),
                            chron::times(as.numeric(x))
                      )
                )
fixed2 <- chron::times(fixed)
guasi
  • 1,461
  • 3
  • 12