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

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?

  • Yes all of them are of the same type. – rjss May 25 '16 at 18:33

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.