2019-12-31

Calculate the difference between alternate rows in R

Problem

We want to calculate the difference between alternate rows in R

df <- 
structure(list(MemId = c(1, 2, 3, 4, 5,6), ET = structure(c(1506829256,
 1506829319, 1506843096,1506843226, 1506850144, 1506853708), class = 
c("POSIXct", "POSIXt"))), .Names = c("MemId", "ET"), row.names = c("1",
 "2", "14", "15", "37", "38"), class = "data.frame")
  MemId                  ET
1      1 2017-10-01 05:40:56
2      2 2017-10-01 05:41:59
14     3 2017-10-01 09:31:36
15     4 2017-10-01 09:33:46
37     5 2017-10-01 11:29:04
38     6 2017-10-01 12:28:28

Solution

First, we create a dummy column with 0 and 1. Then when id == 1 we calculate with difftime the difference between the value of the vector ET and the "previous" value lag(ET).

library(dplyr)
df %>%
  mutate(id = rep_len(0:1, nrow(df))) %>%
  mutate(dif = ifelse(id == 1, difftime(ET, lag(ET), units = "secs"), NA))
  MemId                  ET id  dif
1     1 2017-10-01 05:40:56  0   NA
2     2 2017-10-01 05:41:59  1   63
3     3 2017-10-01 09:31:36  0   NA
4     4 2017-10-01 09:33:46  1  130
5     5 2017-10-01 11:29:04  0   NA
6     6 2017-10-01 12:28:28  1 3564

No hay comentarios:

Publicar un comentario

Nube de datos