Dataframe Manipulation Using Function Tool

Hello! I've included a reproducible example of my dataset. It is a very simple dataframe, and my goal is to create a new dataframe that will give the the difference in time that occurs between each x_ (from start to stop) event. For example, in the first two rows, x_begin occurs at 12.5 seconds and ends (x_end) at 15 seconds. I would like to find a way to get the duration of this event (2.5 seconds), and do this for every x/y/z_begin and x/y/z_end that occurs in the dataframe. I'm thinking this can be done with a simple function, however, I am unsure where to start exactly. I hope this makes sense!

> dput(df)
structure(list(EVENT = c("x_begin", "x_end", "x_begin", "x_end", 
"y_begin", "y_end", "z_begin", "z_end", "y_begin", "y_end ", 
"z_begin", "z_end", "x_begin", "x_end ", "x_begin", "x_end", 
"x_begin", "x_end"), TIME = c(12.5, 15, 18, 34.5, 36, 43, 56, 
108, 111, 141, 144, 151, 156, 231, 265, 289, 301, 333)), class = "data.frame", row.names = c(NA, 
-18L))
suppressPackageStartupMessages({
  library(dplyr)
})

DF <- data.frame(
  EVENT = c("x_begin", "x_end", "x_begin", "x_end", 
 "y_begin", "y_end", "z_begin", "z_end", "y_begin", "y_end ", 
 "z_begin", "z_end", "x_begin", "x_end ", "x_begin", "x_end", 
 "x_begin", "x_end"), 
  TIME = c(12.5, 15, 18, 34.5, 36, 43, 56, 108, 111, 141, 144, 
          151, 156, 231, 265, 289, 301, 333))

DF %>% mutate(DURATION = ifelse(row_number() %% 2, NA, TIME - lag(TIME)))
#>      EVENT  TIME DURATION
#> 1  x_begin  12.5       NA
#> 2    x_end  15.0      2.5
#> 3  x_begin  18.0       NA
#> 4    x_end  34.5     16.5
#> 5  y_begin  36.0       NA
#> 6    y_end  43.0      7.0
#> 7  z_begin  56.0       NA
#> 8    z_end 108.0     52.0
#> 9  y_begin 111.0       NA
#> 10  y_end  141.0     30.0
#> 11 z_begin 144.0       NA
#> 12   z_end 151.0      7.0
#> 13 x_begin 156.0       NA
#> 14  x_end  231.0     75.0
#> 15 x_begin 265.0       NA
#> 16   x_end 289.0     24.0
#> 17 x_begin 301.0       NA
#> 18   x_end 333.0     32.0

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.