Time counting variable

Hi, I have the following vector of time (Hours, Minutes, Seconds) and the following variable (var1). I want to generate a time variable such as var2. Any ideas on that?

   time           var1      var2
02:35:39         0      00:00:00
02:35:41         0      00:00:00
02:35:43         0      00:00:00
02:35:45         0      00:00:00
02:35:46         0      00:00:00
02:35:47         1      00:00:01
02:35:48         1      00:00:02
02:35:49         1      00:00:03
02:35:51         1      00:00:05
02:35:51         1      00:00:05


This returns a period object (see the {lubridate} vignette), which is the best you can do with the time column without an accompanying representation of ymd


the_time <- "02:35:39"
#> [1] "2H 35M 39S"

Created on 2020-11-15 by the reprex package (v0.3.0.9001)

1 Like

Thanks for the answer, but how would you use that code to get var2 ?

It depends on the data object and its content. I assume you have a data frame with a class character column Time, you can create var2 using {dplyr}

my_df %>% mutate(var2 = hms(Time)) -> my_df

This will get you a {lubridate} period object. If you need a datetime object instead, you must prepend a date string to the Time column.

Time is capitalized because it's the name of a built-in function, like df and data, and it's good practice to avoid them in naming your own objects because some operations treat the name as the function rather than your object and throw an error message to the effect that something can't be done with a closure.

1 Like

I like using the hms package when working with time-only components.


var1 <- 0
hms(seconds = var1)
#> 00:00:00

Created on 2020-11-16 by the reprex package (v0.3.0)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.