0

I wrote function below to convert numeric value for seconds to format

HH:MM:SS

    my_to_time <- function(sec_vec_num,hours = T){
      sec_vec = seconds_to_period(sec_vec_num)
      if(hours == T){
        sec_vec = sprintf('%01g:%02g:%02g', sec_vec@hour, minute(sec_vec), second(sec_vec))
      }else{
        sec_vec = sprintf('%01g:%02g', minute(sec_vec), second(sec_vec))
      }
      return(sec_vec)

}

When I try to run this, I get following error though

 Error in as.POSIXlt.numeric(x) : 'origin' must be supplied 

The vector I am converting is numeric class. Not sure how to fix this error.

  • Post 5 values from `the sec_vec_num` vector – Onyambu Dec 08 '21 at 21:37
  • See this useful post https://stackoverflow.com/questions/27312292/convert-seconds-to-days-hoursminutesseconds/27313681 using ``lubridate::seconds_to_period`` – jsirgo Dec 08 '21 at 21:57
  • I tested your code on the `numeric` vector `x <- c(1, 61, 3661, 86399, 86400, 86401)`, and once I had qualified the **`lubridate`** functions with `lubridate::`, my call to `my_to_time(x)` **actually worked**: `"0:00:01" "0:01:01" "1:01:01" "23:59:59" "0:00:00" "0:00:01"`. Are you *sure* your input vector is truly `numeric`? – Greg Dec 08 '21 at 22:06
  • 1
    Found my issue, another package was causing some problem, reload R and loaded only lubridate and the problem was solved. Thanks ! – Gregory Smith Dec 08 '21 at 23:04
  • @GregorySmith Did that other package have a `minute()` or `second()` function (or even a `seconds_to_period()` function)? If so, a way to avoid this in the future is to **fully qualify** all your **`lubridate`** functions like so: `lubridate::seconds_to_period()`, `lubridate::minute()`, `lubridate::second()`. That way, a function like `lubridate::minute()` will never get masked by a `minute()` function from another package, which might work differently from what you expect. – Greg Dec 08 '21 at 23:07

0 Answers0