Home > Net >  R: convert a varialble 'difftime' in seconds to a variable 'difftime' in days
R: convert a varialble 'difftime' in seconds to a variable 'difftime' in days

Time:10-02

I have the following vectorx of class difftime expressing some time spans in seconds:

> x
Time differences in secs
[1]       0       0 7948800       0

> class(x)
[1] "difftime"

I would like to convert the variable so as to express every value in days instead of seconds

How could I get it?

CodePudding user response:

Either use units= as RonakShah suggested,

x <- difftime(Sys.time()   c(0, 100, 3*86400), Sys.time(), units = "days")
x
# Time differences in days
# [1] 0.000000000 0.001157407 3.000000000

or change the units after the fact.

x <- difftime(Sys.time()   c(0, 100, 3*86400), Sys.time())
x
# Time differences in secs
# [1]      0    100 259200
units(x) <- "days"
x
# Time differences in days
# [1] 0.000000000 0.001157407 3.000000000

CodePudding user response:

Use as.numeric and then convert to difftime using units="days" in both. If a numeric output is ok then omit as.difftime at the end of the pipeline.

# test input
secs <- as.difftime(rep(7948800, 3), units = "secs")

secs |> as.numeric(units = "days") |> as.difftime(units = "days")
## Time differences in days
## [1] 92 92 92
  • Related