R:将以秒为单位的变量 'difftime' 转换为以天为单位的变量 'difftime'

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

我有以下矢量x of class difftime 以秒为单位表达一些时间跨度:

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

> class(x)
[1] "difftime"

我想转换变量以便以天而不是秒来表示每个值

我怎样才能得到它?

按照 RonakShah 的建议使用 units=

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

或事后更改单位。

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

使用 as.numeric,然后在两者中使用 units="days" 转换为 difftime。如果数字输出正常,则在管道末尾省略 as.difftime

# 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