'Simplifying repetitive code in R - how to avoid copy-pasting?
I am learning how to use loops and functions to avoid copy-pasting code. I'm having a hard time with this example though; how would you reduce this?
train$Name <- replace(train$Name, train$Name == "crop", 1)
train$Name <- replace(train$Name, train$Name == "pasture", 2)
train$Name <- replace(train$Name, train$Name == "secondary forest", 3)
train$Name <- replace(train$Name, train$Name == "mature forest", 4)
#edit: I also have another part of code with a similar issue:
bands <- c('B1', 'B2', 'B3', 'B4', 'B5', 'B7')
filepaths <- paste0('./raw_data/LE07_L2SP_012054_20100211_20200911_02_T1/LE07_L2SP_012054_20100211_20200911_02_T1_', 'SR_', bands, '.TIF')
bandlist <- lapply(filepaths, raster)
...
landsat <- bandlist %>% reduce(inner_join)
saveRDS(landsat, 'landsat_2010.rds')
for example, here I want to go over several files, process them and save them as new dataframes named after their respective years. Is there a way to reduce this - naming each file with its corresponding year?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
