如何用R将int转换为分钟和秒

时间:2018-01-27 13:22:42

标签: r

我在R中有一个数据框,如下所示:

event | time_seconds
001   |    67
002   |   150
003   |   145
004   |   831
005   |   453
006   |    78
...

time_seconds列存储为整数,但我想将其转换为MM:SS(分:秒)格式。目前只有几秒钟,所以003事件是145秒。我想将其转换为02:24。

以下是使用dput

的可重现示例
df <- structure(list(event = c(1, 2, 3, 4, 5, 6), time_seconds = c(67, 
150, 145, 831, 453, 78)), .Names = c("event", "time_seconds"), row.names = c(NA, 
-6L), class = "data.frame")

感谢。

1 个答案:

答案 0 :(得分:1)

使用包lubridate

library(lubridate)
tm <- seconds_to_period(145)
sprintf("%02d:%02d", minute(tm), second(tm))

如果需要转换所有列,请使用:

library(lubridate)
df$time_seconds <- seconds_to_period(df$time_seconds)
df$time_seconds <- sprintf("%02d:%02d", 
                           minute(df$time_seconds), 
                           second(df$time_seconds))

希望有所帮助!