I am struggling with applying a gradient equation over a number of rows between two columns in a matrix. I have shown that I can calculate the gradient correctly between 2 sets of data points (y2-y1/x2-x1) by inputting the variables directly into the function. However, I cannot work out how to loop this down the matrix. For example:
gradient<-function(y,x){
a<-y1-y
b<-x1-x
c=a/b
return(c)
}
My example matrix:
df<-matrix(seq(1:40), ncol=2, nrow = 8)
colnames(df)<-c("x","y")
df
x y
[1,] 1 9
[2,] 2 10
[3,] 3 11
[4,] 4 12
[5,] 5 13
[6,] 6 14
[7,] 7 15
[8,] 8 16
What I would like to do is write a function that would take y2-y1/x2-x1 and output the gradient, this would continue to y3-y2/x3-x2, and so on. Any help on this would be appreciated. I think I am going wrong with the indexing of the variables in the function.
Many thanks, MRF