P9710053
P9710053

Reputation: 11

subtracting consecutive values in R

Basically I have a data like this:

Begin.Time..s.  1.039*** 3.133* 5.156 7.168 9.249 11.362             

End.Time..s.  1.383**  3.437  5.5  7.539 9.546 11.674

I would like to make the following operation:

3.133* - (1.383** - 1.039***)  

And then continue until the end of the data.

Upvotes: 1

Views: 125

Answers (2)

Arun kumar mahesh
Arun kumar mahesh

Reputation: 2359

hope it may be useful from base R

df1$Begin[2:length(df1$Begin)]-(df1$End[1:5]-df1$Begin[1:5])
[1]  2.789  4.852  6.824  8.878 11.065

data

copied from previous OP sotos

Upvotes: 0

Sotos
Sotos

Reputation: 51592

Using the lag function from dplyr, we can do the following,

df$Begin[-1] - na.omit(dplyr::lag(df$End - df$Begin))
#[1]  2.789  4.852  6.824  8.878 11.065

DATA

dput(df)
structure(list(Begin = c(1.039, 3.133, 5.156, 7.168, 9.249, 11.362
), End = c(1.383, 3.437, 5.5, 7.539, 9.546, 11.674)), .Names = c("Begin", 
"End"), row.names = c(NA, -6L), class = "data.frame")

EDIT Based on @nicola's suggestion, a lighter approach would be

df1$Begin[-1]-(df1$End-df1$Begin)[-nrow(df1)]
#[1]  2.789  4.852  6.824  8.878 11.065

Upvotes: 1

Related Questions