I'm running a randomforest on a raster stack/brick in R. I know how to rename individual layers in the stack, but since my stacks have numerous Landsat scenes, I was hoping to loop through the stack. I'm doing this because I want the variable importance plot (varImgPlot) from the randomforest package to display shorter names than the entire raw Landsat code. My code is as follows:
for (i in 1:name_len){
name_var<-names(stack_analyze)[i]
if (nchar(name_var)>18){
name_date<-str_sub(name_var, 18, 26)
name_band<-str_sub(name_var, -2, -1)
new_name<-paste(name_date, name_band, sep = '')
names(stack_analyze)[1]<-new_name
}
else{
print('name small, no change made')
}
}
Some of the layers are derived, so I have an effective, shorter name for them already. I'm trying to select larger layers here and then change them accordingly based on a simple positional str_sub(). When I run this code, it doesn't even work for the first name. It renames to the wrong band name for the first layer, and then doesn't do anything for the rest. I get the correct number of print statements for the shorter names, so at least I know the loop is going through the if statements. Any help to make this work so I don't have to go name dozens of bands manually?