2

I have a list of dataframes. For each dataframe I want to create one new variable or column called uniqueid and I want this unique id to be the name of the dataframe from the list. I have tried the following but it does not work.

# List all shapefiles
dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))

for( i in seq_along(dfs)){
  dfs[[i]]$uniqueid<-print(paste(dfs[[i]]))
}  

When I do the following each dataframe get a uniqueid equals to ID. SO I guess the part that is not working correctly on my code is print(paste(dfs[[i]])) however I can't figure out what the right fix is.

# List all shapefiles
dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))

for( i in seq_along(dfs)){
  dfs[[i]]$uniqueid<-'ID'
}  
0
1

You just have to query your list names at each iteration:

library(sf)
# the files
fl = list.files("/dir_with_shapes", pattern = ".shp", full.names = T)

dfl = lapply(fl, read_sf) # read them in
names(dfl) = basename(fl) # give them the file name

for(i in seq_along(dfl))
   dfl[[i]]$df_name = names(dfl)[i]

df = do.call(rbind, dfl)  # bind them all together
3
  • Elio, thank you for your answer. Unfortunately the .shp are not in the same folder but in several (300+) different folders. Mar 30 at 18:09
  • list.files(..., recursive = TRUE) would work if your files are all within the same parent directory; if you are not merging them all you may choose them by a pattern; besides that, you may try ogrmerge.py from gdal, it's really good for lots of files
    – Elio Diaz
    Mar 30 at 18:14
  • 1
    Brillant, it worked perfectly. Thank you!!! Mar 30 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.