R 减去时间

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)

格式为 'hours':'minutes' 我希望从 'start' 中减去 'stop' 以创建一个名为 'minutes' 的新变量列,它等于'WANT'

中显示的分钟数

这是一个使用 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_))

使用data.table,我们将列转换为ITime,通过与difftime取差,将Reduce转换为numeric

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

-输出

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