Home > Back-end >  How can I convert character vector with time into Time class and get a total amount of time after su
How can I convert character vector with time into Time class and get a total amount of time after su

Time:11-14

I've got a vector and it's class is character. Firstly, I want to convert it into time class, then I want to subset it to two vectors based on the amount of time (I want to have one subset with more than four hours and the subset with less than four hours). Then I want to get the total amount of time in the subsets. I also attach to this question the screenshot of my dataset. Dataset example

CodePudding user response:

Using tidyverse packages, you can use:

library(dplyr)
library(lubridate)

df <- tibble(
    Time = paste(round(runif(18, 0, 10)),
                 sprintf(".0f", round(runif(18, 0, 59))),
                 sprintf(".0f", round(runif(18, 0, 59))),
                 sep = ":")    
)

df %>%
    mutate(
        timevar = hms(Time),
        fourhrs = timevar > hms("4:00:00")
        ) %>%
    group_by(fourhrs) %>%
    summarize(
        sum = seconds_to_period(sum(period_to_seconds(timevar)))
    )

# A tibble: 2 x 2
  fourhrs sum           
* <lgl>   <Period>      
1 FALSE   14H 11M 26S   
2 TRUE    3d 17H 40M 51S
  • Related