[R-sig-Geo] summing rasters with a condition given by other rasters
Ben Tupper
btupper at bigelow.org
Mon May 18 18:55:59 CEST 2015
Hi Martin,
On May 18, 2015, at 12:22 PM, Martin Brandt <martin.brandt at mailbox.org> wrote:
> Hi Eder,
>
> yes, i tried to include na.rm:
>
> sum_segment <- function(x, ...) {
> mean(x[(x[1]+2):(x[2] + 2)], na.rm=TRUE)
> }
>
> but as long my stack contains any NA values, the function will not run with
> calc:
>> s <- calc(b, sum_segment)
> Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
> cannot use this function
>
> or
>
>> s <- calc(b, sum_segment, na.rm=T)
> Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
> cannot use this function. Perhaps add '...' or 'na.rm' to the function
> arguments?
>
> not sure how to make the function run and ignore all NAs..
>
This function is designed to accept further arguments for other functions within the its body. So, if you pass na.rm = TRUE to sum_segment() then it will trickle down, so to speak, to sum(). The following should work for sum or mean.
sum_segment <- function(x, ...) {
sum(x[(x[1]+2):(x[2] + 2)],...)
}
mean_segment <- function(x, ...) {
mean(x[(x[1]+2):(x[2] + 2)],...)
}
s <- calc(b, sum_segment, na.rm = TRUE)
m <- calc(b, mean_segment, na.rm = TRUE)
s
#class : RasterLayer
# dimensions : 77, 101, 7777 (nrow, ncol, ncell)
# resolution : 1, 1 (x, y)
# extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=merc
# data source : in memory
# names : layer
# values : 0, 2295 (min, max)
m
# class : RasterLayer
# dimensions : 77, 101, 7777 (nrow, ncol, ncell)
# resolution : 1, 1 (x, y)
# extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=merc
# data source : in memory
# names : layer
# values : 0, 255 (min, max)
If that doesn't work (whether you use mean() or sum()) then something else is happening and you'll want to post a small runnable example of what you are doing.
Cheers,
Ben
>
>
>
>
> --
> View this message in context: http://r-sig-geo.2731867.n2.nabble.com/summing-rasters-with-a-condition-given-by-other-rasters-tp7588222p7588272.html
> Sent from the R-sig-geo mailing list archive at Nabble.com.
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org
More information about the R-sig-Geo
mailing list