user1959078
user1959078

Reputation: 25

How to calculate the difference between two rows

Basically I have a column in an R dataframe, and I want to find a code to compute the following function:

(i - (i-1)) - ((i+1) - i)

In other words, for the left side of the function I want to subtract the value from the previous row (i-1) from i, and for the right side of the function I want to subtract i from the value from the next row (i+1)

If anyone could help it would be much appreciated.

Upvotes: 2

Views: 2888

Answers (4)

Tom Evans
Tom Evans

Reputation: 563

I've had similar scenarios before. Ideally you should stick to vectorised code, as it's much faster. What I have done is make two new vectors, one shifting everything up one (i-1) or shifting down one (i+1), then using these in a calculation:

i <- (1:5)^2

i.next     <- c(i[2:length(i)],NA)
i.previous <- c(NA,i[1:length(i)-1])

i.calculation <- (i - i.previous) - (i.next - i)

cbind(i,i.next,i.previous,i.calculation)

# i i.next i.previous i.calculation
# [1,]  1      4         NA            NA
# [2,]  4      9          1            -2
# [3,]  9     16          4            -2
# [4,] 16     25          9            -2
# [5,] 25     NA         16            NA

Upvotes: 0

Theodore Lytras
Theodore Lytras

Reputation: 3965

Your description is not clear. If a is a vector, what you are asking would be provided by:

f <- diff(a[-length(a)]) - diff(a[-1])

and would be defined for 1 < i < length(a), thus length(f) = length(a) - 2

Replace a with your data.frame column.

Upvotes: 2

EDi
EDi

Reputation: 13280

Or like this? What should happen on the borders?

x <- (1:5)^2
-diff(diff(x))
# [1] -2 -2 -2

Upvotes: 8

Roland
Roland

Reputation: 132596

Like this?

x <- (1:5)^2
#[1]  1  4  9 16 25
as.vector(filter(x,c(-1,2,-1),sides=1))    
#[1] NA NA -2 -2 -2

Upvotes: 8

Related Questions