2

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

MRF
  • 377
  • 1
  • 4
  • 15
  • Can you show your expected output based on this input? And where does 'n' in your function come from? – Heroka Feb 04 '16 at 15:47
  • 1
    Maybe look at `?diff` to calculate `y2-y1`, `y3-y2` etc. – NicE Feb 04 '16 at 15:49
  • Possible duplicate of [R how can I calculate difference between rows in a data frame](http://stackoverflow.com/questions/16212097/r-how-can-i-calculate-difference-between-rows-in-a-data-frame) – slamballais Feb 04 '16 at 15:51
  • Sorry I think I have got myself confused with the equation I will edit it. The expected output would be a vector containing all the gradients of y(n+1)/y(n)/x(n+1)-x(n) – MRF Feb 04 '16 at 15:54
  • @NicE I will look into diff and see if I can create a function from that. Thank you! – MRF Feb 04 '16 at 16:11
  • 1
    something like that: `diffs <- diff(df); diffs[, 1]/diffs[, 2]`. – Stibu Feb 04 '16 at 16:13
  • Two remarks: 1) `df` is often used as the name for a data frame (for obvious reasons) and I find it therefore confusing that you would call your matrix `df`. 2) 1:40 creates an integer sequence. There is no need for `seq()` in your case. – Stibu Feb 04 '16 at 16:15
  • Thank you for the comments @Stibu, they have been helpful. This problem has been solved. – MRF Feb 04 '16 at 16:33

1 Answers1

1

I hope this works for you. rollapply does the loop.

require(zoo)
A <- matrix(seq(1:40), ncol = 2, nrow = 8)
colnames(A) <- c("x","y")
B <- rollapply(A, width = 2, by = 1, FUN = diff)
C <- B[,"y"]/B[,"x"]   
user5249203
  • 4,436
  • 1
  • 19
  • 45