Question

library(raster)  
r <- raster(nrow=5, ncol=5)  
s <- stack( sapply(1:5, function(i) setValues(r, rnorm(ncell(r), i, 3))))  

Will produce rasterstack that has values in every pixel.

How could I produce a rasterstack that contain NA values?

Was it helpful?

Solution

I read the question as that you would like to introduce some NA values into your rasterStack, but not every value. This function samples random normals from the specified distribution but may also sample NA given a specified probability (set p to 1 in the function to get all NA)...

na_ras <- function( r , p , nl ){
  n <- ncell( r ) - 1  
  s <- stack( sapply( seq_len( nl ) , function(i) setValues( r ,  sample( c( NA , rnorm( n , i , 3 ) ) , prob = c( p , rep( (1-p) / n , n ) ) , replace = TRUE ) ) ) )
  return( s )
}

set.seed(1)
#  10% chance of NA being introduced
out <- na_ras( r , 0.1 , 5 )
out[[1]][]
 [1]  3.83150863  0.95142921  2.16952971  3.34640890  5.53534351  1.98852332
 [7]          NA          NA  2.46228716 -0.86372174  0.86519917  0.08383484
[13]  1.22369495  2.46228716  5.53534351  3.21497412  0.86519917 -1.46140515
[19]  2.16952971  3.46366359          NA  3.34640890  3.21497412  3.75693211
[25]  3.21497412

set.seed(1)
#  80% chance of NA being introduced
out <- na_ras( r , 0.8 , 5 )[[1]][]
out
 [1]        NA        NA        NA  2.727344        NA        NA        NA
 [8]        NA        NA        NA        NA        NA -1.506886        NA
[15]        NA        NA        NA        NA        NA        NA        NA
[22]  5.535344        NA -1.461405        NA

If you just want to make a stack of all NA's just use the [ method with stack....

r[] <- NA
stack( r , r , r , r , r  )
#class       : RasterStack 
#dimensions  : 5, 5, 25, 5  (nrow, ncol, ncell, nlayers)
#resolution  : 72, 36  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 
#names       : layer.1, layer.2, layer.3, layer.4, layer.5 
#min values  :      NA,      NA,      NA,      NA,      NA 
#max values  :      NA,      NA,      NA,      NA,      NA 

OTHER TIPS

Use rep(NA,ncell(r)) rather than rnorm:

s <- stack( sapply(1:5, function(i) setValues(r,     rep(NA,ncell(r)) )) ) 
s
class       : RasterStack 
dimensions  : 5, 5, 25, 5  (nrow, ncol, ncell, nlayers)
resolution  : 72, 36  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 
names       : layer.1, layer.2, layer.3, layer.4, layer.5 
min values  :      NA,      NA,      NA,      NA,      NA 
max values  :      NA,      NA,      NA,      NA,      NA 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top