0

I would like to avoid copy pasting in my code, and I would like to use a string as a name of multiple files.

bands <- c('B1', 'B2', 'B3', 'B4', 'B5')

for (band in bands){
  path <- paste0('./data/landsat/LE07_L2SP_012054_20120217_20200909_02_T1', '_SR_', band, '.tif')
  band <- raster(path)
}

In this case, I understand that I am making a raster called "band" five times. Is there any way I could end up with 5 files called respectively 'B1', 'B2', 'B3', 'B4', 'B5'?

  • 3
    To avoid copy/pasting code, you shouldn't give objects sequential names. I'd suggest reading my answer at [How to make a list of data frames?](https://stackoverflow.com/a/24376207/903061) for an analogous problem where the solution is to put a bunch of data frames in a `list` rather than give them sequential names `df1` `df2` `df3`... – Gregor Thomas Feb 02 '22 at 18:49
  • 1
    You define the `path` variable in the loop, but you don't use it anywhere... – Valeri Voev Feb 02 '22 at 18:52
  • 1
    Also, a minor correction on terminology: a *file* usually means a saved file on disk, like your `.data/landsat/...._SR_B2.tif`. If you read a file into R, in R it is not a file, it is an *object* or *variable*. Since you seem to already have files and you are reading them in, I assume your question is about naming R objects, not about naming files. – Gregor Thomas Feb 02 '22 at 18:56
  • (But if my assumption is wrong and you are trying to write new files to disk, please correct me, and add whatever function you want to use to write files to your question.) – Gregor Thomas Feb 02 '22 at 19:03
  • sorry, there was a small typo, I just fixed it and path is used properly now. thank you Gregor, i understand the terminology better now. I think you solved my issue right there! – Ana Catarina Vitorino Feb 02 '22 at 19:18

1 Answers1

1

You should put your data in a list rather than giving it sequential names.

bands <- c('B1', 'B2', 'B3', 'B4', 'B5')
## paste0 is vectorized, no for loop needed
filepaths <- paste0('./data/landsat/LE07_L2SP_012054_20120217_20200909_02_T1', '_SR_', bands, '.tif')
bandlist <- lapply(filepaths, raster)
names(bandlist) <- bands

You can then refer to individual items of the ist as bandlist[[2]] or bandlist[["B2"]].

Read more about this general idea at How do I make a list of data frames?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294