bvowe
bvowe

Reputation: 3394

R SUBTRACT TIME

data=data.frame(start = c("5:21","14:22","99:99"),
stop=c("6:01","15:00","1:14"),
WANT=c(40, 38, NA)

The format is 'hours':'minutes' and I wish to subtract 'stop' from 'start' to create a new variable column called 'minutes' which equals to the minutes between like shown in 'WANT'

Upvotes: 1

Views: 112

Answers (2)

akrun
akrun

Reputation: 887951

Using data.table, we convert the columns to ITime, Reduce by taking the difference with difftime and convert to numeric

library(data.table)
setDT(data)[, WANT2 := -as.numeric(Reduce(difftime, 
        lapply(.SD, as.ITime))), .SDcols = start:stop]

-output

data
#   start  stop WANT WANT2
#1:  5:21  6:01   40    40
#2: 14:22 15:00   38    38
#3: 99:99  1:14   NA    NA

Upvotes: 3

Bruno
Bruno

Reputation: 4150

Here is one solution using the tidyverse

library(tidyverse)
library(lubridate)

data=data.frame(start = c("5:21","14:22","99:99"),
                stop=c("6:01","15:00","1:14"),
                WANT=c(40, 38, NA)
)

data %>% 
  mutate(across(.cols = c(start,stop),.fns = ms),
         difference = seconds(start - stop),
         difference = if_else(difference < 0,
                              difference * -1,
                              NA_real_))

Upvotes: 1

Related Questions