Lauren Phillips
Lauren Phillips

Reputation: 13

writeRaster function in R is automatically setting (unwanted) maximum value, can I set the max value to null?

I am running into a problem with the "writeRaster" function in the raster package in R. I am importing a raster (TIF) that I made in ArcGIS (a distance to feature raster).

My goal was to resample the distance raster to the correct resolution and extent, then "mask" it with the appropriate raster to crop it to the shape I require. When I check the results of the mask with the basic plot function, everything looks great and I can see that each pixel in the new masked raster has a distance value.

However, when I write this raster to a file using the writeRaster function, the resulting raster looks like "swiss cheese" and has missing values for any distance over 35km. After much reading, I cannot find any documentation to suggest that there is a way to modify the maximum value set by writeRaster---or that it should even be setting a max value. I have included my code and the basic plots below. A big thank you to anyone who attempts to help me with this!

#Read in distance to fresh water raster
distFW <- raster("D:/Academia/Arc Data/Grackle/NicaCR_90mlayers/dist_FW.tif")
[plot(distFW)][1]

#Resample this layer to the desired resolution and template
NiCR_DistFW<-as.integer(resample(distFW,NiCRrast.tmpl,method="ngb"))
#essentially the same as the first plot
[plot(NiCR_DistFW)][2]

#Mask the resampled raster to the desired shape
NiCR.DistFW.mask.utm <- mask(NiCR_DistFW,NiCR_Mask) #with CA countries cut out.
[plot(NiCR.DistFW.mask.utm)][3]

#write raster to file (this is where things get weird)
writeRaster(x=NiCR.DistFW.mask.utm, filename='DistFWmask2.tif', format='GTiff', datatype='INT2S') #a way to ensure INT2S

#read the newly written raster file in to R so we can review it
dFW <-raster("DistFWMask2.tif")
[plot(dFW)_writeRaster_result][4]

[1]: https://i.sstatic.net/v9RkK.jpg
[2]: https://i.sstatic.net/v2DG3.jpg 
[3]: https://i.sstatic.net/cCwJe.jpg
[4]: https://i.sstatic.net/MjWj7.jpg

As you can see from plot 4, an undesirable max value has been set. I was the raster I write to file to look like the one in plot 3, not plot 4.

Thanks in advance for any advice.

Upvotes: 0

Views: 598

Answers (1)

Lauren Phillips
Lauren Phillips

Reputation: 13

Well friends, after taking an hour to detail my question I managed to figure out the answer myself. It had to do with setting the datatype.

INT2S has a maximum value of 32,767

by switching it to INT4S, I capture the full range of values in my raster.

Problem solved!

Upvotes: 1

Related Questions