Read multiple layers of KML file using R

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)

Farid Cheraghi's solution works well. Alternatively, you can use lapply from the apply family of functions (so named because it returns a list) instead of a for loop. If you don't care about saving the process as a new function, you can slim the task to three lines:

lyr <- ogrListLayers("file.KML")
mykml <- lapply(lyr, function(i) readOGR("file.KML", i))
names(mykml) <- lyr

Tags:

Import

R

Ogr

Kml

Rgdal