Search code examples
rrasterterra

create multiband raster using individual rasters in terra


To put individual rasters into single raster as individual layers, I would do this:

library(raster)
    
rast1 <- terra::rast('rast1.tif')
rast2 <- terra::rast('rast2.tif')
rast3 <- terra::rast('rast3.tif')
    
single_raster <- c(rast1, rast2, rast3)
 

How can I do it programtically incase I have many more rasters in the working directory. I tried this:

raster_list <- list.files(pattern = ".tif") # get list of all rasters in my working directory 
temp_vec <- rep(NA, length(raster_list)) # create a empty vector with predefined length 
    
for(r in seq_along(raster_list)){ # run loop and put each raster in the empty vector
      
        raster_file <- raster_list[r]
        temp <- terra::rast(raster_file)
        temp_vec[r] <- temp
 }
    

The temp_vec is still NA and I get below warning.

    Warning messages:
      1: In raster_vec[r] <- temp :
      number of items to replace is not a multiple of replacement length
    2: In raster_vec[r] <- temp :
      number of items to replace is not a multiple of replacement length
    3: In raster_vec[r] <- temp :
      number of items to replace is not a multiple of replacement length
    4: In raster_vec[r] <- temp :
      number of items to replace is not a multiple of replacement length
    5: In raster_vec[r] <- temp :
      number of items to replace is not a multiple of replacement length
    6: In raster_vec[r] <- temp :
      number of items to replace is not a multiple of replacement length
    7: In raster_vec[r] <- temp :
      number of items to replace is not a multiple of replacement length
    8: In raster_vec[r] <- temp :
      number of items to replace is not a multiple of replacement length        

The reason I am doing this so that I can create an animation using the multiband raster and save as a gif as follows:

terra::animate(temp_vec)

Solution

  • With terra, it is very simple:

    terra::rast(raster_list)
    

    So you do not need any loop.

    A reproducible example:

    library(terra)
    
    paths = rep(system.file("ex/elev.tif", package="terra"), 10)
    
    r = rast(paths)
    
    set.seed(3) # for reproducibility
    
    # multiply each layer by a random value (because they are the same in the example)
    r = r * runif(10) # to make animation less boring
    
    animate(r)