Ryan S
Ryan S

Reputation: 35

Convert H:M:S into minutes in a new variable in R

I have a time variable in H:M:S format, and I would like to make a new variable that converts this to only minutes. Ie - 1:30:00 in a new variable will be recorded as 90.

This is what I was using, but isn't running, any suggestions?

library(dplyr)
library(lubridate)
DF <- c("1:00:00", "1:30:00", "00:45:00")
Time <- hms(DF)
DFTime <- Time %>% mutate(TimeMins = hour(Time)*60 + mins(Time))
head(DFTime$TimeMins)

Upvotes: 0

Views: 862

Answers (4)

akrun
akrun

Reputation: 887971

Using as_hms from hms

library(hms)
as.numeric(as_hms(v1))/60
[1] 60 90 45

or using base R

rowSums((read.table(text = v1, sep=":", header = FALSE) * list(3600, 60, 0))/60)
[1] 60 90 45

data

v1 <- c("1:00:00", "1:30:00", "00:45:00")

Upvotes: 1

jay.sf
jay.sf

Reputation: 73802

Using asPOSIXlt in R base.

tt <- as.POSIXlt(paste(Sys.Date(), x))
rowSums(mapply(\(x, y) unclass(tt)[[x]]*y/60, 1:3, c(0, 60, 60^2)))
# [1] 60 90 45

Data:

x <- c("1:00:00", "1:30:00", "00:45:00")

Upvotes: 0

9mat
9mat

Reputation: 1234

I made 2 changes to your code:

  • I use minute function from lubridate instead of mins
  • I convert Time to data frame so that the mutate function can work

library(dplyr)
library(lubridate)
DF <- c("1:00:00", "1:30:00", "00:45:00")
Time <- data.frame(Time = hms(DF))
DFTime <- Time %>% mutate(TimeMins = hour(Time)*60 + minute(Time))
head(DFTime$TimeMins)

# results
# [1] 60 90 45

Upvotes: 0

B. Christian Kamgang
B. Christian Kamgang

Reputation: 6529

You could use the as.Time function (in the data.table package) and the built-in function as.integer:

library(data.table)

DF <- c("1:00:00", "1:30:00", "00:45:00")

as.integer(as.ITime(DF) %/% 60L)
# [1] 60 90 45

Note: The decimal part of the converted time is dropped!!

Upvotes: 0

Related Questions