I want to loop through a list of country names contained world shape file and create individual shapefiles of each country. Then I want perform a calculation on the raster of each shapefile and coerce the results into a dataframe with the country name as an ID variable.
I have written this successfully for an individual country but am struggling to get it to loop correctly.
liech.map <- world.polys[world.polys$NAME == "Liechtenstein",]
plot(liech.map)
rasters <- stack(raster_1, raster_2)
rasters.values <- extract(rasters, liech.map)
df <- as.data.frame(rasters.values)
var <- as.data.frame(weighted.mean(x=df$raster_1, w=df$raster_2, na.rm=TRUE))
What I want to do is extract the list of country names from the world polygon shapefile, create a separate polygon for that country and loop it over every country. Then output 1 dataframe with the `var' in for each country with a country ID.
EDIT
Here is what I've managed to do so far, what I really want to be able to do is feed the following code a list of ID codes/names to loop over. I could of course copy and paste this manually 200-odd times, but this seems such a poor use of time!!
### leichenstein map
## 69.67 sec elapsed
tic()
LTU.map <- world.polys[world.polys$ISO3 == "LTU",]
rasters.values <- extract(rasters, LTU.map)
df <- as.data.frame(rasters.values)
rugged_LTU <- as.data.frame(weighted.mean(x=df$raster_1, w=df$raster_2, na.rm=TRUE))
var_LTU$iso3 <- "LTU"
rm(LTU.map)
toc()
# define master dataframe once
var_master <- var_LTU
### UK map
## 127.31 sec elapsed
tic()
GBR.map <- world.polys[world.polys$ISO3 == "GBR",]
rasters.values <- extract(rasters, GBR.map)
df <- as.data.frame(rasters.values)
rugged_GBR <- as.data.frame(weighted.mean(x=df$raster_1, w=df$raster_2, na.rm=TRUE))
var_GBR$iso3 <- "GBR"
var_master <- rbind(var_master, var_GBR)
rm(GBR.map)
toc()