我有一个名为 Wait.Time 的列,其中包含 HMS lubridate 格式的持续时间
如何将此列转换为仅小时? IE。如果我的观察之一是 2H 30M 0S,我怎样才能让它变成 2.5?这不需要保留为类格式 - 它可以很好地更改为数字。
您应该使用
Wait.Time
检查 class()
的类型以确定格式。
可能是
POSIXct
。该解决方案应该适用于 POSIXct
。减去参考时间(可能是 min()
)并使用 as.numeric(x, units = "hours")
强制转换为数字。
单位的可能值显示在
difftime
的文档中: units = c("auto", "secs", "mins", "hours", "days", "weeks")
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
x <- seq(Sys.time(), Sys.time() + hours(5), by = 300)
class(x)
#> [1] "POSIXct" "POSIXt"
(x - min(x)) |>
as.numeric(units = "secs")
#> [1] 0 300 600 900 1200 1500 1800 2100 2400 2700 3000 3300
#> [13] 3600 3900 4200 4500 4800 5100 5400 5700 6000 6300 6600 6900
#> [25] 7200 7500 7800 8100 8400 8700 9000 9300 9600 9900 10200 10500
#> [37] 10800 11100 11400 11700 12000 12300 12600 12900 13200 13500 13800 14100
#> [49] 14400 14700 15000 15300 15600 15900 16200 16500 16800 17100 17400 17700
#> [61] 18000
(x - min(x)) |>
as.numeric(units = "hours")
#> [1] 0.00000000 0.08333333 0.16666667 0.25000000 0.33333333 0.41666667
#> [7] 0.50000000 0.58333333 0.66666667 0.75000000 0.83333333 0.91666667
#> [13] 1.00000000 1.08333333 1.16666667 1.25000000 1.33333333 1.41666667
#> [19] 1.50000000 1.58333333 1.66666667 1.75000000 1.83333333 1.91666667
#> [25] 2.00000000 2.08333333 2.16666667 2.25000000 2.33333333 2.41666667
#> [31] 2.50000000 2.58333333 2.66666667 2.75000000 2.83333333 2.91666667
#> [37] 3.00000000 3.08333333 3.16666667 3.25000000 3.33333333 3.41666667
#> [43] 3.50000000 3.58333333 3.66666667 3.75000000 3.83333333 3.91666667
#> [49] 4.00000000 4.08333333 4.16666667 4.25000000 4.33333333 4.41666667
#> [55] 4.50000000 4.58333333 4.66666667 4.75000000 4.83333333 4.91666667
#> [61] 5.00000000
创建于 2024-04-26,使用 reprex v2.1.0