0

So I'm extracting data from a rasterbrick I made using the method from this question: How to extract data from a RasterBrick?

In addition to obtaining the data from the layer given by the date, I want to extract the data from months prior. In my best guess I do this by doing something like this:

sapply(1:nrow(pts), function(i){extract(b, cbind(pts$x[i],pts$y[i]), layer=pts$layerindex[i-1], nl=1)})

So it the extracting should look at layerindex i-1, this should then give the data for one month earlier. So a point with layerindex = 5, should look at layer 5-1 = 4.
However it doesn't do this and seems to give either some random number or a duplicate from months prior. What would be the correct way to go about this?

BSteen
  • 5
  • 1

1 Answers1

0

Your code is taking the value from the layer of the previous point, not the previous layer.

To see that imagine we are looking at the point in row 2 (i=2). your code that indicates the layer is pts$layerindex[i-1], which is pts$layerindex[1]. In other words, the layer of the point in row 1.

The fix is easy enough. For clarity I will write the function separetely:

foo = function(i) extract(b, cbind(pts$x[i],pts$y[i]), layer=pts$layerindex[i]-1, nl=1)
sapply(1:nrow(pts), foo)

I have not tested it, but this should be all.

JMenezes
  • 1,004
  • 1
  • 6
  • 13