Home > Back-end >  How to add a new column to express results between "Start time" in the next row minus &quo
How to add a new column to express results between "Start time" in the next row minus &quo

Time:11-14

How to add a new column to express results between "Start time" in the next row minus "End time" in the previous row? Thank you very much

enter image description here

CodePudding user response:

You can try sapply.

dat$result <- c( sapply( 2:nrow(dat), function(x) 
                   dat$start_time[x] - dat$end_time[(x-1)] ), NA )

dat
            start_time            end_time   result
1  2021-11-09 00:19:15 2021-11-03 05:51:58 5.772245
2  2021-11-09 00:24:00 2021-11-03 07:26:37 5.674387
3  2021-11-08 23:37:44 2021-11-03 05:36:39 5.710625
4  2021-11-08 22:39:57 2021-11-03 05:57:00 5.677801
5  2021-11-08 22:13:02 2021-11-03 07:35:49 5.617558
6  2021-11-08 22:25:06 2021-11-03 06:05:02 5.680220
7  2021-11-08 22:24:33 2021-11-03 07:20:53 5.678322
8  2021-11-08 23:37:40 2021-11-03 05:05:11 5.814352
9  2021-11-09 00:37:51 2021-11-03 06:44:09 5.692847
10 2021-11-08 23:21:51 2021-11-03 05:17:13       NA

Data:

dat <- structure(list(start_time = structure(c(1636413555.55965, 1636413840.55965,
1636411064.55965, 1636407597.55965, 1636405982.55965, 1636406706.55965,
1636406673.55965, 1636411060.55965, 1636414671.55965, 1636410111.55965
), class = c("POSIXct", "POSIXt")), end_time = structure(c(1635915118.55965,
1635920797.55965, 1635914199.55965, 1635915420.55965, 1635921349.55965,
1635915902.55965, 1635920453.55965, 1635912311.55965, 1635918249.55965,
1635913033.55965), class = c("POSIXct", "POSIXt"))), row.names = c(NA,
-10L), class = "data.frame")

CodePudding user response:

Assuming your start and end time are date objects you can simply do

library(tidyverse)
dat %>%
  mutate(diff = lead(start_time) - end_time)
  •  Tags:  
  • r
  • Related