Subsetting a SpatialLinesDataFrame With 115 Features Into Individual SpatialLineDataFrames


I have a SpatialLinesDataFrame (Shapefiles) with 115 features. I am trying to figure out, if it is possible, to write some sort loop that would enable me to select and save out each of the features individually with file names that would be referenced in one of the columns.

For example, I have a trail.shp file with 115 different trails that I would like to subset into 115 individual trail.shp files, based on the names of the trails.

I know how to do it individually, the example below uses my real data:

sanitasvalley<- subset(boulder_trails, TRAILNAME == "Sanitas Valley")

But I hope that I can make this process more efficient with a coding solution instead of having to go one-by-one.

Here is a general example of my data.

trailname <- ("trail1", "trail2", "trail3")
trailtype <- ("mountain", "flat", "hilly")
parking <- ("no", "yes", "no")
trails <- data.frame(accessname, trailtype, parking)

I would like to select each trail, and save it out as the name that appears under the "trail name" column i.e., trail1.shp

Thanks for looking

This example doesn't save a file, it creates an object on memory, for the same result you could use something like this

boulder_trails %>% 
    group_split(TRAILNAME) %>% 
    walk2(boulder_trails$TRAILNAME, ~assign(as.character(.y), .x, envir = globalenv()))

I don't have any similar shp file at hand to try saving subsets of it, and BTW your sample data doesn't even produce a dataframe (invalid code syntax), could you take a look into it?

Hello, when I run the code, I get the following error message:

Error in UseMethod("group_split") :
no applicable method for 'group_split' applied to an object of class "c('SpatialLinesDataFrame', 'SpatialLines', 'Spatial', 'SpatialVector')"

Sorry I should have included my code:

boulder_trails2 %>% 
  group_split(TRAILNAME) %>% 
  walk2(boulder_trails2$TRAILNAME, ~assign(as.character(.y), .x, 
                                           file = paste0("~/Desktop/boulder_map/subset_trails/"),
                                                                               envir = globalenv()))

Sorry, as I said before I don't have a shp file to test my code, and your sample data is not adequate for the task, so I have no means to help you any further.

The only thing I can say about your code is that the assign() function doesn't take a file argument (it doesn't save files to disk)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.