Scijens
Scijens

Reputation: 561

Convert time format with "x hours y minutes" to numeric

I have a variable indicating time since event and it is coded like this:

time_since_event <- c("18 m", "56 m", "2 h 30 m", "18 h 2 m")

I want it to be numeric and to always indicate the number of minutes since the event:

time_since_event_min <- c(18,56,150,1082)

Upvotes: 2

Views: 291

Answers (3)

akrun
akrun

Reputation: 887163

We could extract the components and get the sum

library(lubridate)
v1 <- as.period(toupper(time_since_event))
v1@hour * 60 + v1@minute
#[1]   18   56  150 1082

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

You can use lubridate functions :

library(lubridate)
(time_since_event %>% toupper %>% period %>% period_to_seconds())/60
#[1]   18   56  150 1082

Upvotes: 5

Allan Cameron
Allan Cameron

Reputation: 173858

You could use strsplit:

time_since_event <- c("18 m", "56 m", "2 h 30 m", "18 h 2 m")
sapply(strsplit(time_since_event, "\\D+"), 
       function(x) {
         x <- as.numeric(x);
         if(length(x) == 2) return(60 * x[1] + x[2]) else return(x)
       })
#> [1]   18   56  150 1082

Upvotes: 3

Related Questions