Search code examples
rtidyverselubridate

Converting time from text to numbers R


I have a questionnaire that I want to estimate the meantime the respondents spent submitting. I receive the data in the format of the responsetime variable below:

mydata <- tibble(
id = c(1:10),
responsetime = c("24 minutes 4 seconds", "1 hour 2 minutes 55 seconds", "15 minutes 5 seconds", 
                 "2 hours 45 minutes 4 seconds", "55 minutes 23 seconds", "5 minutes 55 seconds", 
                 "10 minutes 34 seconds", "27 minutes 11 seconds", "1 hour 6 minutes 57 seconds", 
                  "45 minutes 45 seconds")
)

I want to estimate the meantime of the responsetime variable, but am having trouble converting the text to integers.


Solution

  • You can convert to lubridate::period object

    library(lubridate)
    period(mydata$responsetime)
    
     #[1] "24M 4S"    "1H 2M 55S" "15M 5S"    "2H 45M 4S" "55M 23S"   "5M 55S"   
     #[7] "10M 34S"   "27M 11S"   "1H 6M 57S" "45M 45S" 
    

    To get average response time in minutes you can do -

    mean(period_to_seconds(period(mydata$responsetime)))/60
    #[1] 47.88833