Home > Blockchain >  Avoiding copy paste - how to make multiple files with different names
Avoiding copy paste - how to make multiple files with different names

Time:02-03

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'?

CodePudding user response:

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?

  •  Tags:  
  • Related