I am working in R and having some difficulties with extracting values from a raster layer. What I am trying to do is aggregate satellite night light data from pixel to polygons. However, when I attempt to extract the data I am unable to process it into a, for me, convenient format such as a data frame. Below is an example of what I've done so far, using some of the suggestions on similar questions on this website.
The satellite data is taken from NOAA. The code to download the shape file for Sudan comes from this question.
## Load libraries and code
library(maptools)
library(raster)
library(sp)
source("getCountries.R")
## Load data
# Sudanese provinces (Sudan before 2011)
source("code/getCountries.R")
adm1<-getCountries("SDN",level=1)
# Night light data
d<-raster("F141998.v4b_web.stable_lights.avg_vis.tif")
## Transform projection
projection(d)<-proj4string(adm1)
## Crop raster to include only Sudan
e=extent(adm1)
r=crop(d,e)
## Plot data for visual inspection
colfunc <- colorRampPalette(c("black", "white"))
par(mar=c(3,6,3,6))
plot(r,col=colfunc(20))
plot(adm1,border="White",add=T)
They don't call it dark Africa for no reason. Khartoum is clearly visible though. Next step is to get the night light emission per province.
## Extract the data
data<-extract(r,adm1,FUN=max,sp=TRUE)
According to the manual the sp=TRUE
argument should return a spatial object if fun
is not NULL. Maybe I am missing something here but fun
seems to be not NULL, nonetheless I get the following error:
Warning message: In .local(x, y, ...) : argument sp=TRUE is ignored if fun=NULL
The resulting object in this case is a list which isn't really useful. I can set df=TRUE
which will give me a large dataframe with all pixels assigned to a province. However, I reckon there must be some method to aggregate the data in one go rather than using several intermediate steps.
Does anyone have a good suggestion on the best way to aggregated pixel data to polygon level? The example above only uses one raster layer but eventually I want to apply to a stack of layers (multiple years).