2

I am trying to load a set of shapefiles into R using a loop. I am trying to find a way to name the loaded shapefile using the name as it stored in the vector used for the loop.

When I run the following code the loaded shapefile is named "s" instead of "spain", "france", or "portugal".

I have tried something like paste(print(s)) but it is not successful.

Make list of all names

shapefiles<-c("spain","france","portugal")

Load files

for (s in shapefiles) {

combine<-paste(s,"borders.shp",sep = "")

s<-st_read(paste("./repository/",print(combine), sep=""))

}

SOLUTION:

Make list of all names

shapefiles<-c("spain","france","portugal")

Load files

for (s in 1:length(shapefiles)) {

combine<-paste(shapefiles[s],"borders.shp",sep = "")

assign(shapefiles[s],st_read(paste("./repository/",print(combine), sep=""))) }

Marcel Campion
  • 247
  • 1
  • 7

2 Answers2

1

I ran into the same problem and I solved it using the assign() function.

E.g.

# Get the names of the  shp
shapefiles<-c("spain","france","portugal")

# The assign() function!!!!    :D
for(i in 1:length(shapefiles)){
  
  assign(shapefiles[i], st_read(paste("./repository/shapefile.shp",print(combine), sep=""))) 
  
}

Something like that. Just I am not sure with the st_read() function but you can modify it for your problem.

FrsLry
  • 348
  • 4
  • 19
  • Hi @FrsLry, thank you for answering this question. Your code is interesting but the "i" is numeric when I call `combine<-paste(i,"borders.shp",sep = "")` instead of being "spain" or "portugal". Do you have a fix? – Marcel Campion Jan 15 '21 at 10:28
  • 1
    If you want to use combine I would use: `combine<-paste(shapefiles[i],"borders.shp",sep = "")`. I guess that you want a filename like `franceborders.shp` – FrsLry Jan 15 '21 at 10:32
0

I found a fix:

All into a list

dflist<-Filter(is.data.frame, as.list(.GlobalEnv))

Create a mapid column

dflist<-Map(function(df, x){df$mapeid<-gsub("(_\\d).*","\\1",x); df}, dflist, names(dflist))

From this discussion [https://stackoverflow.com/questions/36946822/add-new-column-to-data-frame-through-loop-in-r]

Marcel Campion
  • 247
  • 1
  • 7