[R-sig-Geo] Create a mask with 1 deg latitudinal bands

Michael Sumner mdsumner at gmail.com
Wed Jun 19 00:53:55 CEST 2013

On Tue, Jun 18, 2013 at 10:54 PM, Panday, Prajjwal <PPanday at clarku.edu> wrote:
> Thanks Mike. It works great. Could you explain what the second command does?
> Prajjwal

Please keep the discussion on list.

?setValues  "You can use the setValues function to assign values to a
Raster* object"
?rowFromCell "These functions get the row and/or column number from a
cell number of a Raster* object"

Basically, we address the individual rows with rowFromCell by passing
in every cell number, 1:ncell(r) returns a rows*col vector of
1:(rows*col) that identifies every cell, and with this rowFromCell
gives us the index of the row in which each cell lies (that's what we

Then setValues() puts the row index into our raster,
replacing/initializing them (it doesn't matter which) and returns a
new raster with the same extent and resolution of our starting raster.

The raster package provides so many nice helpers like this, but still
it might be worth adding something like
rowIndex(raster)/colIndex(raster) to do all that work for us, and
matching Xvalues(raster)/Yvalues(raster) to put in the native
coordinates instead. Then you could also have
longitudes(raster)/latitudes(raster) to do the same for unprojected
rasters, or reproject on the fly in the obvious way. I'll have a look
at that (or wait to be shown that the functions are already there!).

Cheers, Mike.

> ________________________________________
> From: Michael Sumner [mdsumner at gmail.com]
> Sent: Monday, June 17, 2013 8:41 PM
> To: Panday, Prajjwal
> Cc: r-sig-geo at r-project.org
> Subject: Re: [R-sig-Geo] Create a mask with 1 deg latitudinal bands
> How about this?
> library(raster)
> ## quick way to get 1-degree raster with your extents
> r <- crop(raster(), extent(-58,-48,-17,-2))
> r2 <- setValues(r, rowFromCell(r, 1:ncell(r)))
> plot(r2)
> On Tue, Jun 18, 2013 at 1:10 AM, ppanday <ppanday at clarku.edu> wrote:
>> Hi, I am trying to create a mask within a specified extent [ext <-
>> extent(-58,-48,-17,-2)] that has 1 degree latitudinal band masks. So every 1
>> degree is a different number category. Eventually, I want to use it in zonal
>> (as a mask) to obtain zonal statistics.
>> I have a way that is a bit roundabout and I was trying to see if there is a
>> more straightforward option.
>> Sincerely
>> Prajjwal
>> --
>> View this message in context: http://r-sig-geo.2731867.n2.nabble.com/Create-a-mask-with-1-deg-latitudinal-bands-tp7583803.html
>> Sent from the R-sig-geo mailing list archive at Nabble.com.
>> _______________________________________________
>> R-sig-Geo mailing list
>> R-sig-Geo at r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> --
> Michael Sumner
> Hobart, Australia
> e-mail: mdsumner at gmail.com

Michael Sumner
Hobart, Australia
e-mail: mdsumner at gmail.com

More information about the R-sig-Geo mailing list