When I stack a raster (using the stack function in the raster R package) that has a nodata value of -3.4e 38 and then write the raster to a tif, the nodata value becomes apart of the value range for the raster (min of -3.4028234663853e 38).The minimum value of the original raster was 0. How do I get my code to recognize the nodata value and not incorporate it as a value in the output raster? Note that the output raster also has a nodata value (when I look at the raster properties in QGIS) of -3.4e 38.
Here is my code:
temp_10m<-raster("temp_10m.tif")
stack<-stack(temp_10m)
save(stack, file = "temp_test.Rdata")
writeRaster(stack, filename=names(stack), bylayer=TRUE,format="GTiff", overwrite=TRUE)
CodePudding user response:
I tried to use the NAvalue
function from raster
, but was unable to get the plot to recognize the NA. Maybe you can try setting the value of NA by changing to NA. Here is an example:
library(raster)
#test dataset
set.seed(32)
dem1 <- raster(matrix(runif(9, 1, 10), 3, 3))
dem1[sample(1:9,2)] <- -3.4e 38
dem2 <- raster(matrix(runif(9, 1, 20), 3, 3))
dem3 <- raster(matrix(runif(9, 1, 100), 3, 3))
dem3[sample(1:8,1)] <- -3.4e 38
dem4 <- raster(matrix(runif(9, 1, 300), 3, 3))
dem_stacked <- stack(dem1, dem2, dem3, dem4)
#set the Na value
NAvalue(dem_stacked) <- -3.4e 38
#check the NA values
NAvalue(dem_stacked)
#> [1] -3.4e 38 -3.4e 38 -3.4e 38 -3.4e 38
#still shows up in plot
plot(dem_stacked)
#change -3.4e 38 to NA
dem_stacked[dem_stacked < -3e 38] <- NA
#values removed from plot
plot(dem_stacked)
CodePudding user response:
To my knowledge, TIF, as well as GIF and JPG formats only allow integers in the range 0:255 ( or 0:2^n for small n) , and with good reason: there's only so far you can drive video displays.
The more important problem here is that you are trying to create an image with pixel entries "no data" which doesn't make any sense in the real world. Consider the case of a film negative which has a corner torn off. You can make a print but there will have to be some color in the missing area.
Pick a default, be it white or black or whatever, and assign that to your "missing" regions.