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"
3 Answers 3
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]])
-
Thank you this is what I get; Error: unexpected ')' in: "for(i in 1:length(layer_list$name)) { layers_sf[[layer_list$name[i]]] = read_sf(dsn = 'pathtomygdb.gdb', layer = layer_list$name[i]))" > } Error: unexpected '}' in "}" Please see my updates on my questionpuredata– puredata2020年09月17日 15:53:33 +00:00Commented Sep 17, 2020 at 15:53
-
I corrected the code, there was a parenthesis in excess, now it should workElio Diaz– Elio Diaz2020年09月17日 15:59:51 +00:00Commented Sep 17, 2020 at 15:59
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!
Replace the for-loop with the purrr
package.
st_layers
will list all of the names within your gdb and then purrr::map
uses the list of names with st_read
to read each vector into R from your gdb.
library(sf)
path<-"path/to/your.gdb"
gdb<-st_layers(path)
list_of_features<-purrr::map(gdb$name,~st_read(dsn=path,layer=.))
for
function or any of theapply
family of functions?scd <- st_read(dsn='/path/to.gdb')
scdl <- st_layers(dsn='/path/to.gdb')
for(i in scd) {
st_as_sf(scd)
save(scd, file="layer")
st_write(i)
``` scdl gives me the names of every layer. but I need to save those layers as separate files which, I couldn't figure out. I assumed looping over scdl would work but it doesn't work.