How to change MM:HH:SS to minute while the variable tupe are <char>

31 Views Asked by At

My dataset "ride_history" has a variable name "total_time_spend". Here the values are in HH:MM:SS (example: 03:26:30) format and the variable type is "char". I want to convert it into a new variable "minute" and add it in the dataset. How to do it?

I have used "separate" function to make new colum Hour,minute,sec. But those column are not "numeric". That's why I use "as.numeric" to calculate a new variable "total_minute". After that, I used "cbind" to make new dataset!

1

There are 1 best solutions below

3
stefan On BEST ANSWER

Using hms and lubridate packages you could do:

library(hms)
library(lubridate)

dat <- data.frame(
  total_time_spend = "03:26:30"
)

dat$minute <- lubridate::minute(hms::as_hms(dat$total_time_spend))

str(dat)
#> 'data.frame':    1 obs. of  2 variables:
#>  $ total_time_spend: chr "03:26:30"
#>  $ minute          : int 26

EDIT A second option would be to use tidyr::separate to split the time string into its components:

dat |> 
  tidyr::separate(total_time_spend, into = c("hour", "minute", "second"), sep = ":", 
           convert = TRUE, remove = FALSE)
#> Warning: Expected 3 pieces. Missing pieces filled with `NA` in 1 rows [2].
#>   total_time_spend hour minute second
#> 1         03:26:30    3     26     30
#> 2            04:27    4     27     NA