Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R apply and get values from previous row

I'd like to use the previous row value for a calculation involving the current row. The matrix looks something like:

      A   B
[1,]  1   2
[2,]  2   3
[3,]  3   4 
[4,]  4   5
[5,]  5   6

I want to do the following operation: (cell[i]/cell[i-1])-1, essentially calculating the % change (-1 to 1) from the current row to the previous (excluding the first row).

The output should look like:

         C      D
[1,]    NA     NA
[2,]   1.0    0.5
[3,]   0.5   0.33 
[4,]  0.33   0.25
[5,]  0.25   0.20

This can be accomplished easily using for-loops, but I am working with large data sets so I would like to use apply (or other inbuilt functions) for performance and cleaner code.

So far I've come up with:

test.perc <- sapply(test, function(x,y) x-x[y])

But it's not working.

Any ideas?

Thanks.

like image 376
Travis Liew Avatar asked Feb 15 '23 04:02

Travis Liew


1 Answers

df/rbind(c(NA,NA), df[-nrow(df),]) - 1

will work.

like image 102
James King Avatar answered Feb 28 '23 10:02

James King