2

I am trying to write rasters in asc format using raster and terra R package. I am using the following code

library(terra)
library(raster)

f <- system.file("external/test.grd", package="raster")
r1 <- raster(f)
plot(r1)
writeRaster(r1, paste('Try1','.asc', sep=''), overwrite=TRUE)

r2 <- rast(f)
writeRaster(r2, paste('Try2','.asc', sep=''), overwrite=TRUE)

Now if you open the Try1.asc, you will see that the NODATA_value is -3.4e+38 while it is nan in Try2.asc enter image description here

enter image description here

nan is creating problem when I am using these rasters in other software. I have tried using NAflag = -3.4e+38 which is not working as well enter image description here

Now how can I have the output like raster package using terra R package while using writeRaster function?

UseR10085
  • 7,120
  • 3
  • 24
  • 54

2 Answers2

1

That is a bug. It works with terra 1.5.40 and higher

library(terra)
#terra 1.5.40   

r <- rast(ncol=2, nrow=2, vals=c(0,NA,1,NA))
f <- "test.asc"

r = writeRaster(r, f, overwrite=TRUE, NAflag=-99) 
readLines(f)
#[1] "ncols        2"                
#[2] "nrows        2"                
#[3] "xllcorner    -180.000000000000"
#[4] "yllcorner    -90.000000000000" 
#[5] "dx           180.000000000000" 
#[6] "dy           90.000000000000"  
#[7] "NODATA_value  -99"             
#[8] " 0.0 -99"                      
#[9] " 1 -99"                        

r
#class       : SpatRaster 
#dimensions  : 2, 2, 1  (nrow, ncol, nlyr)
#resolution  : 180, 90  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84 
#source      : test.asc 
#name        : lyr.1 
#min value   :     0 
#max value   :     1 
 
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
0

It appears you have to actively manage your data, not unreasonable:

r3 <- rast(f, opts='NODATA_value=-3.4e+38') # didn't have desired effect
r4 <- classify(r3, cbind(NaN, -3.4e+38))
writeRaster(r4, paste('TRY3','.asc', sep = ''), overwrite=TRUE)
# in gedit
ncols        80
nrows        115
xllcorner    178400.000000000000
yllcorner    329400.000000000000
cellsize     40.000000000000
NODATA_value  nan
 -3.3999999521443642491e+38 -3.3999999521443642491e+38 -3.3999999521443642491e+38 -3.3999999521443642491e+38 -3.3999999521443642491e+38 -3.3999999521443642491e+38

packageVersion('terra')
[1] ‘1.5.39’

-3.4e+83 generally makes plots, well, not great. But classify is the tool. Probably better ways that others will share.

Chris
  • 1,647
  • 1
  • 18
  • 25