How to combine state-level shapefiles from the united states census bureau into a nationwide shape

前端 未结 2 1797
别跟我提以往
别跟我提以往 2021-02-09 14:49

The census bureau doesn\'t provide a nationwide shapefile of public use microdata areas (the smallest geography available on the American Community Survey). I tried combining t

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-09 15:33

    Here's another approach, which includes a short cut for obtaining the FTP directory listing. As @Pop mentioned, the key is to ensure that the IDs are all unique.

    library(RCurl) 
    library(rgdal)
    
    # get the directory listing
    u <- 'ftp://ftp2.census.gov/geo/tiger/TIGER2014/PUMA/'
    f <- paste0(u, strsplit(getURL(u, ftp.use.epsv = FALSE, ftplistonly = TRUE), 
                            '\\s+')[[1]])
    
    # download and extract to tempdir/shps
    invisible(sapply(f, function(x) {
      path <- file.path(tempdir(), basename(x))
      download.file(x, destfile=path, mode = 'wb')
      unzip(path, exdir=file.path(tempdir(), 'shps'))
    }))
    
    # read in all shps, and prepend shapefile name to IDs
    shps <- lapply(sub('\\.zip', '', basename(f)), function(x) {
      shp <- readOGR(file.path(tempdir(), 'shps'), x)
      shp <- spChFIDs(shp, paste0(x, '_', sapply(slot(shp, "polygons"), slot, "ID")))
      shp
    })
    
    # rbind to a single object
    shp <- do.call(rbind, as.list(shps))
    
    # plot (note: clipping to contiguous states for display purposes)
    plot(shp, axes=T, xlim=c(-130, -60), ylim=c(20, 50), las=1)
    
    # write out to wd/USA.shp
    writeOGR(shp, '.', 'USA', 'ESRI Shapefile')
    

    unified shp

提交回复
热议问题