8

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?

1
  • Yes all of them are of the same type.
    – rjss
    Commented May 25, 2016 at 18:33

2 Answers 2

6

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)
0
5

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 and acknowledge you have read our privacy policy.

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