我有一个从excel导出的变量(trips)in factor数据类型中的列(ride_length)为HH:MM:SS

  • 本文关键字:SS ride MM length HH in excel 有一个 变量 factor trips r
  • 更新时间 :
  • 英文 :

#using the glimpse function
ride_length       : Factor w/ 21865 levels
#using the str function
$ ride_length        <fct> 0:12:57, 0:18:29, 1:37:18, 0:13:52, 0:37:17, 0:47:21

我希望新的输出作为在下面阅读

$ ride_length        <???> 12.95, 18.4833, 97.3, 13.8666, 37.2833, 47.35

我们可以转换为hms并除以60

as.numeric(hms::as_hms(as.character(trips$ride_length))/60)
[1] 12.95000 18.48333 97.30000 13.86667 37.28333 47.35000

数据

trips <- structure(list(ride_length = structure(c(1L, 3L, 6L, 2L, 4L, 
5L), .Label = c("0:12:57", "0:13:52", "0:18:29", "0:37:17", "0:47:21", 
"1:37:18"), class = "factor")), class = "data.frame", row.names = c(NA, 
-6L))

使用基本R,可以进行

with(strptime(as.character(trips$ride_length), "%H:%M:%OS"), 60 * hour + min + sec / 60)

尽管存在限制,因为strptime需要从0到23的小时、从0到59的分钟以及从0到60的秒。如果该约束不满足,那么,使用lubridate,您可以执行

library("lubridate")
as.numeric(hms(as.character(trips$ride_length)), "minutes")

有了chron包,我们可以(感谢akrun提供的数据(:

library(chron)
library(dplyr)
ride_length <- trips %>% 
mutate(ride_length_minutes = 60 * 24 * as.numeric(times(ride_length))) %>% 
pull(ride_length_minutes)
ride_length
[1] 12.95000 18.48333 97.30000 13.86667 37.28333 47.35000

或作为新列:

library(chron)
library(dplyr)
trips %>% 
mutate(ride_length_minutes = 60 * 24 * as.numeric(times(ride_length)))
ride_length ride_length_minutes
1     0:12:57            12.95000
2     0:18:29            18.48333
3     1:37:18            97.30000
4     0:13:52            13.86667
5     0:37:17            37.28333
6     0:47:21            47.35000

最新更新