Search code examples
rrasterspatialr-rasterterra

How to export the values of a SpatRaster into .txt-file using the terra-package?


I got a .tif dataset with land cover classifications (so categorical values) which I want to replace with another value (integers) and export these values into a .txt-file following the ASCII format (this is required by the model I want to use the output for).

1. Is there any opportunity to export the actual values of the SpatRaster?

2. And are there any concerns about exporting to a .txt-file by defining the filename?

I was able to replace the values by using subst(), but when trying to export I was only able to produce output containing the ID.

r <- rast(nrows=3, ncols=3)
values(r) <- sample(3, ncell(r), replace=TRUE)
cls <- data.frame(id=1:3, cover=c("forest", "water", "urban"))
levels(r) <- cls


replacement <- c(10,20,30)
r_replaced <- subst(r,levels(r)[[1]]$cover, replacement)

writeRaster(r_replaced, "test.txt", filetype = "AAIGrid")

The output looks like this

ncols        3
nrows        3
xllcorner    -180.000000000000
yllcorner    -90.000000000000
dx           120.000000000000
dy           60.000000000000
NODATA_value 255
 6 4 6
 4 4 4
 4 5 4

but I actually want it to look like this

ncols        3
nrows        3
xllcorner    -180.000000000000
yllcorner    -90.000000000000
dx           120.000000000000
dy           60.000000000000
NODATA_value 255
 30 10 30
 10 10 10
 10 20 10

Solution

  • You can do this (note raw=TRUE)

    # levels(r)[[1]][,1] == 1:3
    
    r_replaced <- subst(r, c(1:3), c(10,20,30), raw=TRUE)
    
    writeRaster(r_replaced, "test.asc", NAflag=-999, overwrite=T)
    

    Result

    readLines("test.asc", 10)
    # [1] "ncols        3"                
    # [2] "nrows        3"                
    # [3] "xllcorner    -180.000000000000"
    # [4] "yllcorner    -90.000000000000" 
    # [5] "dx           120.000000000000" 
    # [6] "dy           60.000000000000"  
    # [7] "NODATA_value  -999"            
    # [8] " 10.0 30 20"                   
    # [9] " 10 10 30"                     
    #[10] " 10 30 30"       
    

    The problem with your approach is that r_replaced is still a categorical raster (see levels(r_replaced) for your code). You can also start out by removing the categories

    levels(r) <- NULL
    

    Although, with this example, you could also do

    rr <- r * 10
    writeRaster(rr, "test.asc", NAflag=-99, overwrite=TRUE)