For loop in R to download map data (raster package)

ぃ、小莉子 提交于 2020-03-04 09:30:09

问题


I'm currently trying to plot a map of Africa using the different countries and plotting them together. I use the following code to download and plot a single country, which works perfect:

CMR <- getData('GADM', country='CMR', level=0)
plot(CMR)

I wanted to do this now for all the different countries in Africa. So I've made a charactervector (charafr) containing all these GADM codes and now I want to try to save them all to a seperate vector using a for loop. I'm a bit puzzled on how to assign these to seperate vectors. This is what I have:

for (i in 1:53){
     africancountries[i] <- getData('GADM', country=charafr[i], level=0)
}

This doesn't work and I'm not 100% sure on how to adjust the formatting so all the spatialpolygondataframes will be in a different vector.

Does anybody have an idea?

Thanks in advance.


回答1:


You can do it like this

library(raster)
charafr <- c('RWA', 'BDI', 'UGA') 

With a for loop:

ac <- list()
for (i in 1:length(charafr)){
     ac[[i]] <- getData('GADM', country=charafr[i], level=0)
}
allac <- do.call("bind", ac)

plot(allac)

Or, with lapply, more concise, but less readable:

charafr <- c('RWA', 'BDI', 'UGA') 
allac2 <- do.call("bind", lapply(charafr, function(x)  getData('GADM', country=x, level=0)))

To save this to disk as a shapefile, you can do

shapefile(allac2, 'allac.shp')



回答2:


I don't have the charafr vector so I'm not totally sure if this will function (I tested with a 2 element vector), but based on your comments above it should work. This will result in a single SpatialPolygonsDataFrame and it can be written out using writeOGR if you want a shapefile. Note this will function the same way as the list, in that if you want a specific country you need to call it using list syntax. However, it does have the spdf class.

uid <- 1

for ( i in 1:53 ) {

  africancountry <- getData( 'GADM', country=charafr[i], level=0 )

  n <- length( slot( africancountry, "polygons" ) )

  africancountry <- spChFIDs( obj = africancountry, x= as.character( uid:( uid+n-1 ) ) )

  uid <- uid + n

  if(i == 1){ africancountries <- africancountry } else { africancountries <- rbind( africancountries,africancountry ) }
}


来源:https://stackoverflow.com/questions/34878807/for-loop-in-r-to-download-map-data-raster-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!