[GIS] Read multiple layers of KML file using R

importkmlogrrrgdal

I have a KML that 3970 layers. I am trying to read it into R using the following script:

library(rgdal)
lyr <- ogrListLayers("file.KML")
mykml <- readOGR("file.KML","Layer1")

This works but what if I want to read all layers; something like:

mykml <- readOGR("file.KML",lyr)

Is there a way to accomplish this?

Best Answer

A simple function can do that for you. Here's how:

allKmlLayers <- function(kmlfile){
  lyr <- ogrListLayers(kmlfile)
  mykml <- list()
  for (i in 1:length(lyr)) {
    mykml[i] <- readOGR(kmlfile,lyr[i])
  }
  names(mykml) <- lyr
  return(mykml)
}

use it with:

kmlfile <- "se\\file.KML"
mykml <- allKmlLayers(kmlfile)