TransWikia.com

Save layers from a gdb as sf objects in a loop

Geographic Information Systems Asked on December 21, 2020

I’m taking an R class and I have an assignment that I’m trying to figure out. Instructor wants us to save all layers in a gdb file as sf objects. He told us that we should use loops.

I’m able to import the gdb file using

scd <- st_read(dsn='/path/to.gdb')

And I’m also able to list layers using

scdl <- st_layers(dsn='/path/to.gdb')

Update:

  
  st_read(dsn = '/path/to.gdb', layer=i)
  feat <- st_read(code here)
}

i

this is what I have done so far which loops over the layernames. but when I try to assign them to objects using feat <- st_read(code here) line, it breaks my loop.

"Error in CPL_read_ogr(dsn, layer, query, as.character(options), quiet, :
Expecting a single value: [extent=5].
In addition: Warning message:
In if (nchar(dsn) < 1) { :
the condition has length > 1 and only the first element will be used"

2 Answers

In the following code the sf objects are read and added to a list, which is a safe way of reading things in a for loop.

library(sf)
layer_list = st_layers("to.gdb")

layers_sf = list()
for(i in 1:length(layer_list$name)) {
  layers_sf[[layer_list$name[i]]] = read_sf(dsn = "to.gdb", layer = layer_list$name[i])
}
 # a plot f the first to test the list object `layers_sf`:
plot(layers_sf[[1]])

Answered by Elio Diaz on December 21, 2020

I had my class and this is what I was able to come up with, which worked and got accepted;

scdl <- st_layers('path/to.gdb')

for(i in scdl$name) {
  
  feat <- st_read(dsn = 'path/to.gdb', layer=i)
  plot(feat)
}

My professor said function lapply would have been the best solution but this works as well. Thank you for all the help and suggestions, much appreciated!

Answered by puredata on December 21, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP