title: Creating a non-rectangular raster in R
body: <p>In my analysis I have to loop over the cell id (i.e. cell numbers) of a raster, this is non-optional and done in a different software setting (BUGScode) which I am not to fluent in. My raster has to fit a shapefile (my study area) exactly, otherwise I would be looping over cell numbers I have no values for or interest in and then... well you know what happens then ;).</p>
  <p><strong>reproducible example</strong></p>
  <pre><code>### get a shapefile
  GER&lt;-getData(&quot;GADM&quot;, country=&quot;DEU&quot;,level=1,download=T,path=getwd())
  
  ### make a raster
  raster&lt;-raster(ext=extent(GER), vals=0, crs=crs(GER))
  
  plot(raster);plot(GER, add=T)
  
  ### now make the raster fit exactly to the German borders
  mask.raster&lt;-mask(raster, GER)
  
  plot(mask.raster) ### looks right, but WAIT
  plot(mask.raster, colNA=&quot;black&quot;) ### the border cells were only set to NA, which is problematic if your raster contains NA in the first place, i.e. if you used rasterize to count points in the raster cells
  
  trim.raster&lt;-trim(raster, values=NA)
  
  plot(trim.raster, colNA=&quot;black&quot;); plot(GER, add=T) ### trim only trims complete rows/columns from the raster
  
  crop.raster&lt;-crop(raster, GER)
  
  plot(crop.raster, colNA=&quot;black&quot;);plot(GER, add=T) ### crop only crops to extent
  
  </code></pre>
  <p>How do I get my raster to exactly fit the outline of my study area and thus <strong>not</strong> be rectangular?</p>
  <p><em>This is done regularly in all kinds of GIS-software, but I am currently limited to R.</em></p>