title: calculating area of most suitable raster habitat in R
body: <p>I have run Maxent for multiple species under present conditions and also under future climate change scenarios. I was quantifying changes between present and future suitable habitat using the nicheOverlap function and Schoener's D statistic. Quite a few of the organisms in my study are just moving farther up mountains so there is a lot of overlap as the future distribution is inside the present distribution (just occupying less area at higher elevations). By looking at the ascii files in QGIS I can see that there is less suitable habitat in terms of area in the future, so I want to quantify this. I have scoured the internet for a good way to calculate area for rasters and never found anything that perfectly suited my fancy. I therefore wrote up something that is an amalgamation of bits and pieces of various scripts. It is pasted below. </p>
  
  <p>Two questions:
  1) do you all agree this is doing what I think it is doing (calculating area in square kilometers)?
  2) is there a way to simplify this? Specifically you'll see I go from a raster to a dataframe back to raster? Maybe I could stay in rasters?</p>
  
  <p>Thanks for any input!</p>
  
  <p>Rebecca</p>
  
  <pre><code>####
  library(raster)
  
  #load rasters
  m &lt;- raster("SpeciesA_avg.asc")
  mf &lt;- raster("SpeciesA_future_layers_avg.asc")
  
  #change to dataframe
  m.df &lt;- as.data.frame(m, xy=TRUE)
  
  #get rid of NAs
  m.df1 &lt;- na.omit(m.df)
  
  #keep only cells that that have a suitability score above 0.5 (scores range from 0 to 1)
  m.df2 &lt;- m.df1[m.df1$SpeciesA_avg&gt; 0.5,]
  
  #re-rasterize just the suitable area
  m.raster &lt;- rasterFromXYZ(m.df2)
  
  ##same as above but for future projection
  mf.df &lt;- as.data.frame(mf, xy=TRUE)
  mf.df1 &lt;- na.omit(mf.df)
  mf.df2 &lt;- mf.df1[mf.df1$SpeciesA_future_layers_avg&gt;0.5,]
  mf.raster &lt;-rasterFromXYZ(mf.df2)
  
  #get sizes of all cells in current distribution raster
  #note my original layers were 30 seconds or 1 km2. 
  cell_size&lt;-area(m.raster, na.rm=TRUE, weights=FALSE)
  
  #delete NAs from all raster cells. It looks like these come back when switching from dataframe to raster
  cell_size1&lt;-cell_size[!is.na(cell_size)]
  
  #compute area [km2] of all cells in raster
  raster_area_present&lt;-length(cell_size1)*median(cell_size1)
  raster_area_present
  
  #get sizes of all cells in future raster [km2]
  cell_size&lt;-area(mf.raster, na.rm=TRUE, weights=FALSE)
  
  #delete NAs from vector of all raster cells
  cell_size1&lt;-cell_size[!is.na(cell_size)]
  
  #compute area [km2] of all cells in geo_raster
  raster_area_future&lt;-length(cell_size1)*median(cell_size1)
  raster_area_future
  
  ##calculate change in area
  dif_area &lt;- raster_area_present - raster_area_future
  dif_area
  </code></pre>