mpvalenc
mpvalenc

Reputation: 61

Create loop or function that calculates through every observation and performs another calculation based off the result of the first calculation

I have a vector called time: Time <- c(2.444582, 2.445613, 2.446644, 2.447675, 2.448706, 2.449737, 2.769358, 2.770389, 2.771420, 2.772451, 2.773482, 2.774513, 2.775544, 2.776575, 2.777606, 3.087606, 3.093759, 3.099134, 3.100493, 3.478295, 3.484896, 3.482309)

I want to create a loop or function that subtracts every observation from the previous one, for example: 2.445613-2.444582, 2.446644-2.445613, 2.447675-2.446644 etc. Then if the difference between each observation is greater than 0.2 (i.e 2.769358-2.448706 = 0.320), I want to get the difference between the lesser number and the first number in that sequence (i.e. 2.449737-2.444582, 2.777606-2.769358, 3.100493-3.087606) and the difference from the last number in the vector and the first number in the particular sequence (i.e. 3.482309-3.478295)

My desired output from this Time vector would be: 0.005155, 0.008248, 0.012887, 0.004014

Upvotes: 0

Views: 39

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Here is one way without loops :

We first get the positions where the difference between current observation and the previous one is greater than 0.2. We then create index using this position to subset values from Time vector.

inds <- which(diff(Time) > 0.2)
Time[c(inds, length(Time))] - Time[c(1, inds + 1)]
#[1] 0.005155 0.008248 0.012887 0.004014

Upvotes: 1

Related Questions