1

I have to build a 8 bits raster as ascii (.asc). I'm trying to use R writeRaster fonction, however it is not working:

Reproducible example:

library(raster)

rr <- raster(matrix(sample(1:100, 100),10,10), xmn=0, xmx=10, ymn=0, ymx=10)

writeRaster(rr, "D:/temp/test_tif.asc", datatype="INT1U", overwrite=T)
dataType(raster("D:/temp/test_tif.asc"))
 [1] "INT4S"

This is not working, however when using tif, the same script works:

writeRaster(rr, "D:/temp/test_tif.tif", datatype="INT1U", overwrite=T)
dataType(raster("D:/temp/test_tif.tif"))
 [1] "INT1U"

Any idea why it isn't working for asc?

  • 1
    ASCII files do not have bit depth the same way image formats do and I do not believe that the raster package can encode an asc file. It would require specific coding to define differend bit depths for flat files. You could open the asc output in something like Notepad++ (with word wrap turned off) and encode to INT1U that way. – Jeffrey Evans Sep 5 '18 at 13:35
2

From the GDAL AAIGRID driver docs:

By default, the datatype returned for AAIGRID datasets by GDAL is autodetected, and set to Float32 for grid with floating point values or Int32 otherwise. This is done by analysing the format of the NODATA value and, if needed, the data of the grid. From GDAL 1.8.0, you can explicitly specify the datatype by setting the AAIGRID_DATATYPE configuration option (Int32, Float32 and Float64 values are supported currently)

it doesn't mention the sign, but my experiments show that even an AAIGRID file with a positive NODATA value and all positive grid values is returned as INT4S (a 4-byte signed integer, aka Int32) by dataType().

  • I'm not sure I get all of your point, but GDAL deals very well with asc in Bytes: "C:\OSGeo4W64\bin\gdal_translate.exe" -ot "Byte" -of "GTiff" "D:/temp/test_tif.tif" "D:/temp/test_asc_gdal.asc" convert properly the dataType (dataType(raster("D:/temp/test_asc_gdal.asc"))). It doesn't make sense to me that the raster package cannot, could it be a bug or something forgotten? – Bastien Sep 5 '18 at 17:31
  • I've also, after reading your comment, change the nodatavalue from the raster (with: rr@file@nodatavalue <- 0) before writing it and it's not helping. – Bastien Sep 5 '18 at 17:33
  • 1
    That gdal_translate will read the test_tif.tf and create test_asc_gdal.asc also as a TIFF file because you used -o GTiff. Its not creating an AAIGRID ascii file. That's what you get if you writeRaster with a .asc extension. – Spacedman Sep 5 '18 at 19:00
  • interesting... Indeed, using -of "AAIGrid" in my gdal statement leads to a "INT4S" type again. Thanks. – Bastien Sep 5 '18 at 19:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.