#using the glimpse function ride_length : Factor w/ 21865 levels #using the str function $ ride_length 0:12:57, 0:18:29, 1:37:18, 0:13:52, 0:37:17, 0:47:21
I would like the new output to read below as
$ ride_length 12.95, 18.4833, 97.3, 13.8666, 37.2833, 47.35
CodePudding user response:
We may convert to hms
and divide by 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
data
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))
CodePudding user response:
With base R, you can do
with(strptime(as.character(trips$ride_length), "%H:%M:%OS"), 60 * hour min sec / 60)
though there are limitations, as strptime
requires hours from 0 to 23, minutes from 0 to 59, and seconds from 0 to 60. If that constraint isn't satisfied, then, with lubridate
, you can do
library("lubridate")
as.numeric(hms(as.character(trips$ride_length)), "minutes")
CodePudding user response:
With chron
package we could (data from akrun many thanks):
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