Navya
Navya

Reputation: 287

How to add minutes to time in R

I have a data frame with time(e.g: 10.24) and minute(e.g:31) columns.

I want to add those two columns. Resultant column would be 10.24+31(min)=10.55. I tried with but it is giving wrong times.

dput(stack_data)
structure(list(time = c("10:24", "10:40"), timeInMin = c(31L, 
23L)), row.names = c(19L, 23L), class = "data.frame")

I have tried like this:

stack_data$time <- (hm(stack_data$time))
stack_data$timeInMin <- hms((stack_data$time) + (stack_data$timeInMin))

Output:

time         timeInMin
10H 24M 0S    10:24:31
10H 40M 0S    10:40:23

I am getting a wrong answer. Can you please suggest me to how to do it? Thanks.

Upvotes: 2

Views: 2250

Answers (1)

akrun
akrun

Reputation: 887068

We can use as.ITime from data.table

library(data.table)
stack_data$time <- as.ITime(paste0(stack_data$time, ":00"))
stack_data$timeInMin <- stack_data$time +
                    as.ITime(paste0("00:", stack_data$timeInMin, ":00"))
stack_data$timeInMin
#[1] "10:55:00" "11:03:00"

Or using hm

library(lubridate)
hm(stack_data$time)  + minutes(stack_data$timeInMin)
#[1] "10H 55M 0S" "10H 63M 0S"

Upvotes: 2

Related Questions