# R - How to get raster values across a latitude band

Let's say I have a raster like this:

``````library(raster)
r <- raster(ncols=15, nrows=15)
values(r) <- runif(ncell(r)) * 1:ncell(r)
plot(r)
``````

I need to:

1. find the latitude point closest to a given value, say -50. In the example above, that latitude point would be -48;
2. extract the values for all the longitude points across that latitude band (i.e. the red line in the figure below). The desired output would be a data frame with the longitude points and the extracted values.

Any hints on how to achieve that?

Make a sample raster:

``````> r = raster()
> r[] = 10 * (1:ncell(r))
``````

Note the value of the cell is going to be 10 times the cell number...

Which row is latitude -20?

``````> row = rowFromY(r, -20)
> row
 111
``````

Row 111. Ok. What are the cell numbers for row 111?

``````> cells = cellFromRow(r, row)
> cells[1:10]
 39601 39602 39603 39604 39605 39606 39607 39608 39609 39610
``````

and what are the values in those cells?

``````> r[cells[1:10]]
 396010 396020 396030 396040 396050 396060 396070 396080 396090 396100
``````

Ten times the cell number. You can check this is true for all the cells, not just the first ten as above. Ok we got all the rows and columns and commas in the right place.

Now where's those cells?

``````> xy = xyFromCell(r,cells)
> xy[1:10,]
x     y
[1,] -179.5 -20.5
[2,] -178.5 -20.5
[3,] -177.5 -20.5
[4,] -176.5 -20.5
[5,] -175.5 -20.5
[6,] -174.5 -20.5
[7,] -173.5 -20.5
[8,] -172.5 -20.5
[9,] -171.5 -20.5
[10,] -170.5 -20.5
``````

Constant y value, great, variable x value, super.

Put it all together:

``````> output = data.frame(xy, r[cells])