0

I am trying to mosaic multiple multi band datasets into a single large multi band raster in R.I tried to do it with this code but it returns a single band image.

library(sp)  
library(raster)  
library(rgdal)  
setwd("C:\\Projects\\Rice-fallow_4_states\\Bihar\\S1")  
x <- list.files(".\\", pattern='tif$',
                    full.names = TRUE) # list all the rasters  
X1<- as.list(x)    

allrasters1 <- lapply(X1, raster)  
x.mosaic <- do.call(merge,allrasters1)   
names(x.mosaic)  
x.mosaic  
plot(x.mosaic)  
UseR10085
  • 7,120
  • 3
  • 24
  • 54

3 Answers3

1

I will suggest that you should use terra in palce of raster package. terra is much faster comapred to raster. You can use the following code

library(terra) 

setwd("C:\\Projects\\Rice-fallow_4_states\\Bihar\\S1")  
x <- list.files(".\\", pattern='tif$',
                full.names = TRUE) # list all the rasters  

allrasters1 <- lapply(x, rast)  
x.mosaic <- do.call(mosaic, allrasters1)  
names(x.mosaic)  
x.mosaic  
plot(x.mosaic) 
UseR10085
  • 7,120
  • 3
  • 24
  • 54
1

This is how you can do that with terra (the replacement of "raster")

library(terra)
ff <- list.files(".\\", pattern='tif$',
                    full.names = TRUE) 
x <- sprc(ff) 
m <- mosaic(x)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
0

When you load rasters in R using raster(), it only loads one layer of the image. If you want to load the entire multi-band image, use either stack() or brick(). I believe brick() is the most correct one for images with multiple bands, but I don't deal with those often, so I have yet to find a meaningful difference between that and stack().

JMenezes
  • 1,004
  • 1
  • 6
  • 13