How do you change a vector from CHR to INT in R?

182 Views Asked by At

New user of R here so forgive my ignorance but I've hit a bit of a bind!

I am currently working on a data set called Q1 which has a column for Start_Time that is displaying HH:MM except its vector is CHR and not INT or NUM.

I am currently trying to convert it to an INT or NUM so that I may change its format to HH:MM:SS but am having trouble doing so.

For Example:

Date <- c("11/22/22", "11/23/22", "11/24/22", "11/25/22")
Start_Time <- c("12:30", "14:25", "09:45", "17:50")
Q1 <- data.frame(Date, Start_Time)

So far I have tried

 strptime(Q1$Start_Time, format = "%H:%M:%S")

 as.integer(Q1$Start_Time)

 Q1 <- transform(Q1, Start_Time = as.integer(Start_Time))

 Q1 <- transform(Q1, Start_Time = as.numeric(Start_Time))

But all of these have returned a value of NA through my whole column or given me an error about NAs introduced by coercion.

Does anyone have any ideas? Any help would be greatly appreciated! Thank You!

1

There are 1 best solutions below

1
malcorl On

as user @onyambu pointed out this question was answered by them here

But to also sum it up using as.ITime from the data.table worked perfectly

as.numeric(data.table::as.ITime(Q1$Start_Time))

and returned the values for

45000 51900 35100 64200

For anyone curious about converting it back to a HH:MM:SS format I used mutate

Q1 <- Q1 %>% mutate(Start_Time = hms::hms(Start_Time))

Thanks to everyone who pitched in!