将格式Hh Mm Ss的因子转换为持续时间 [英] Convert factor of format Hh Mm Ss to time duration
问题描述
我正在使用一个数据帧,该数据帧具有一个名为"Duration"的变量,其值的格式为:
I'm working with a data frame that has a variable called "Duration" with values in the format:
1h 7m 46s
1h 7m 46s
0h 16m 41s
0h 16m 41s
..等等.默认情况下,该列的格式设置为因素",我想知道如何将其转换为实际持续时间.我希望能够计算持续时间的平均值和总和.
..and so on. The column is formatted as a "factor" by default, and I'm wondering how to convert it to an actual duration. I'd like to be able to compute averages and sums of the durations.
推荐答案
请考虑使用 <带有
Consider converting the times to strings with an as.character()
cast. Once your times are strings you can convert them into DateTime
objects with the strptime
command, e.g.
> s <- "1h 7m 46s"
> tfmt <- "%Hh %Mm %Ss"
> t1 <- strptime(s, format=tfmt)
> s <- "0h 16m 41s"
> t2 <- strptime(s, format=tfmt)
以这种格式保存数据非常方便,因为现在有了用于处理它们的工具
Having the data in this format is handy as there are then tools for working with them
> t1
[1] "2015-01-30 01:07:46"
> t2
[1] "2015-01-30 00:16:41"
> t1 - t2
Time difference of 51.08333 mins
> difftime(t1, t2, units="secs")
Time difference of 3065 secs
这篇关于将格式Hh Mm Ss的因子转换为持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!