1
2# setMethod("arith", signature(x="SpatRaster"),
3## not exported
4arith <- function(x, fun, ..., filename="", overwrite=FALSE, wopt=list())  {
5
6	out <- rast(x)
7	nc <- ncol(x)
8	readStart(x)
9	on.exit(readStop(x))
10
11# # test the shape of the output by testing with one row
12	v <- readValues(x, round(0.5*nrow(x)), 1, 1, nc, mat=TRUE)
13	r <- try(fun(as.vector(v), ...))
14	if (inherits(r, "try-error")) {
15		error("arith", "'fun' is not valid")
16	}
17	if (!is.vector(r)) {
18		error("arith", "'fun' does not return a vector")
19	}
20	if (!(is.numeric(r) | is.logical(r))) {
21		error("arith", "'fun' does not return a numeric vector")
22	}
23	if (length(r) != length(v)) {
24		error("arith", "'fun' does not return the same number of values as the input")
25	}
26
27	b <- writeStart(out, filename, overwrite, wopt=wopt)
28	for (i in 1:b$n) {
29		v <- readValues(x, b$row[i], b$nrows[i], 1, nc, TRUE)
30		v <- fun(as.vector(v), ...)
31		writeValues(out, v, b$row[i], b$nrows[i])
32	}
33	writeStop(out)
34}
35
36# )
37
38