[R-sig-Geo] Cannot correctly assign Data type of upper left cell in ascii grid with writeRaster

Michael Koehler michael.koehler at nw-fva.de
Wed May 17 10:21:26 CEST 2017


Dear list,

  I encountered a problem when trying to write an Ascii-grid of integers 
with raster::writeRaster.
When using that function, the upper left cell (only that cell!) in the 
resulting ascii grid will always
  be a floating point number, even if I convert the whole raster to 
integers before.

  However, when I convert the raster to a SpatialPixelDataFrame and 
write the Ascii file with
  maptools::writeAsciiGrid, the resulting upper left cell will be 
correctly saved as an integer.
So Is this a bug or am I doing something wrong here?

  Here is a reproducible example:

library(raster)
library(maptools)
library(SDMTools)
library(adehabitat)

# create raster

m <- matrix(c(-999,-999,-999,-999,-999,-999.999,-999.9,-999,1,6,
               -999,-999,-999,7,1,6,7,2,6,3,
               4,7,3,4,5,3,7,9,3,8,
               9,3,6,8,3,4,7,3,7,8,
               3,3,-999.999,7,5,3,2,8,9,8,
               7,6,2,6,5,2,2,7,7,7,
               4,7,2,5,7,7,7,3,3,5,
               7,6,7,5,-999,6,5,2,3,2,
               4,9,2,5,5,8,3,3,1,2,
               5,2,6,5,1,5,3,7,7,2),nrow=10, ncol=10, byrow = T)

r <- raster(m)
values(r)<-as.integer(values(r))

#------------------------------------------------------
# write the raster and read the resulting file in again
writeRaster(r, "Test_writeRaster.asc",NAflag =-999,overwrite=T)
a<-read.table("Test_writeRaster.asc",stringsAsFactors = F)

a[7,] # upper left cell in the ascii file is a floating point number!

#------------------------------------------------------
# convert, write with writeAsciiGrid and read the resulting file in again
asc <- asc.from.raster(r) # convert to asc
rasc <- asc2spixdf(asc)   # convert to SpatialPixelDataFrame

writeAsciiGrid(rasc,"Test_writeAsciiGrid.asc", na.value =-999)
a<-read.table("Test_writeAsciiGrid.asc",stringsAsFactors = F)

a[7,] # upper left cell in the ascii file is a

# R version 3.2.5 (2016-04-14)
# Platform: i386-w64-mingw32/i386 (32-bit)
# Running under: Windows 7 x64 (build 7601) Service Pack 1
#
# locale:
# [1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United 
States.1252
# [3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
# [5] LC_TIME=English_United States.1252
#
# attached base packages:
# [1] stats     graphics  grDevices utils     datasets  methods base
#
# loaded via a namespace (and not attached):
# [1] tools_3.2.5

-- 
Michael Köhler, PhD



More information about the R-sig-Geo mailing list