Search code examples
rlapplyshapefiler-raster

How to reproject a list of shapefiles (SpatialLinesDataFrame) in R


I read a list of shapefiles (SpatialLinesDataFrame) onto R. Now I am trying to reproject this list to a ndifferent EPSG but I just can't seem to have it work. I have tried with lapply and looping through the list but none seem to work, which keep giving the errors I show below.

I know my example is not reproducible, but I might just be missing something very obvious because I could not find a straight forward answer to this.

EPSG_102033 <- "+proj=aea +lat_1=-5 +lat_2=-42 +lat_0=-32 +lon_0=-60 +x_0=0 +y_0=0 +ellps=aust_SA +units=m +no_defs" # CRS EPSG:102033 string

files <- list.files(files_path, pattern = ".shp$", full.names = TRUE)

roads <- setNames(lapply(files, shapefile), tools::file_path_sans_ext(basename(files))) # this gives a list of three SpatialLinesDataFrame S4 objects

### I have tried:

roads <- lapply(files, function(x) {x <- spTransform(x, CRSobj = EPSG_102033);x}) 

# which gives: Error in (function (classes, fdef, mtable) : 
unable to find an inherited method for function ‘spTransform’ for signature ‘"character", "character"’

### Also tried:

for (i in length(roads)){
  roads[[i]] <- spTransform(roads[i],  CRSobj = EPSG_102033) 
}

# which gives: Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘spTransform’ for signature ‘"list", "character"’

What am I missing?

Thanks!


Solution

  • Have you tried using st_transform instead of spTransform? Check the class of your objects, the former is the "newer version" of reprojection from the package sf and the latter is from an older generation, hence the "unable to find inherited method" error. There was a similar issue from this question. The following should work:

    library(sf)
    EPSG_102033 <- "+proj=aea +lat_1=-5 +lat_2=-42 +lat_0=-32 +lon_0=-60 +x_0=0 +y_0=0 +ellps=aust_SA +units=m +no_defs" # CRS EPSG:102033 string
    
    files <- list.files(files_path, pattern = ".shp$", full.names = TRUE)
    
    roads <- setNames(lapply(files, shapefile), tools::file_path_sans_ext(basename(files))) # this gives a list of three SpatialLinesDataFrame S4 objects
    
    ### Method 1
    
    roads <- lapply(files, function(x) {x <- st_transform(x, CRSobj = EPSG_102033);x}) 
    
    
    ### Method 2
    
    for (i in length(roads)){
      roads[[i]] <- st_transform(roads[i],  CRSobj = EPSG_102033) 
    }
    

    Hope that helps!