Skip to content

R+SAGA formula to subtract two raster

2 messages · Alessandro, Alexander Brenning

#
Hi Alessandro,

SAGA has a grid_calculus library. RSAGA provides a wrapper function 
rsaga.grid.calculus, and even rsaga.linear.combination as a more 
convenient version when you want to apply linear models to stacks of 
grids. See ?rsaga.grid.calculus, there's also some example code.

Here some code for your problem of subtracting grids. I am playing 
around with two small identical grids temp1.sgrd and temp2.sgrd and want 
to show that their difference is zero.


library(RSAGA)

rsaga.grid.calculus(in.grids = c("temp1","temp2"),
     out.grid = "result", formula = ~a-b)
# formula could also be  formula = "a+b"
# 'a' refers to the first grid from in.grids,
# 'b' to the second one, etc.

# Same result:
#rsaga.linear.combination( c("temp1", "temp2"), "result",
#    coef = c(1,-1))

# Let's have a look at the data in R
# (if the grid is not too large...):
rsaga.sgrd.to.esri("result", prec = 1)
res = read.ascii.grid("result", return.header = FALSE)
summary(as.vector(res)) # in my case, all ==0 because temp1=temp2


Note that there's also a wrapper function rsaga.close.gaps for the 
module that you are using in the following piece of code:

 > # filter the missing values using neighbours:
 >
 > rsaga.geoprocessor(lib="grid_tools", module=7,
 > param=list(INPUT="DEM_1.sgrd", RESULT="DEM_1_f.sgrd", THRESHOLD=0.1))


I hope this helps.
  Alex
Alessandro wrote: