Search code examples
rr-sf

Export all sf (dataframes) objects from global environment from R


I have a bunch of sf data frames in my global enviornment, I am able to export them all as csv, but i want to export them all as shapefiles instead.

I have tried manually st_write one object and it works. Now I want to bulk export all the objects in my Glob Env and save them as corresponding .shp in my working directory. Any help on how to bulk export into shapefiles?

Just as a ref, my global environment has something like 50 elements, so it is impossible to manually export them all. ;aybe creating a list of sf dataframes coukd do?

Thanks

I have tried saving as dataframes (list = c(is.data.frame, .globenv)), but I absolutely need to export as shp, and not as df list.


Solution

  • Probably not winning a price for elegance herewith, but essentially iterating over the objects in your environment, ensuring the desired class and writing them as shp to disk using the object's name seems to do the trick:

    objs <- ls() 
    
    for (obj in objs) {
      
      if (all(class(get(obj)) == c("sf", "data.frame"))) {
        
        fname <- paste0(obj, ".shp")
        
        sf::st_write(get(obj), fname)
      }
    }