[R-sig-Geo] summing rasters with a condition given by other rasters
Ben Tupper
btupper at bigelow.org
Sun May 10 19:02:15 CEST 2015
Hi,
On May 10, 2015, at 7:37 AM, Martin Brandt <martin.brandt at mailbox.org> wrote:
> Hi Ben,
>
> many thanks for the detailed answer. The code works fine, but when I use
> rasters for eos and sos instead of numbers, i get an error:
>
>
>
> b <- brick(system.file("external/rlogo.grd", package="raster"))
>
> b <- addLayer(b,b,b)
> b
>
> sos <- raster(system.file("external/rlogo.grd", package="raster"))
> eos <- raster(system.file("external/rlogo.grd", package="raster"))
>
>
> sum_segment <- function(x, from = sos, to = eos, ...) {
> sum(x[from:to],...)
> }
>
> s <- calc(b, sum_segment)
>
> Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
> cannot use this function
>
> am I doing something wrong?
Yes, as tempting as it is to do otherwise you really do have to use numeric position indices. Inside the function sum_segment the value of x is simple a numeric vector. Within the scope of the function the context of the pixels embedded in the raster object is temporarily "lost" - they are just a vector of numbers.
To work with the calc() function you must first compute the position indices for sos and eos using which().
sos <- which(names(b) == "blue.1") # you would substitue the name of your layer for blue.1
eos <- which(names(b) == "green.3") # and again for green.3
Cheers,
Ben
>
>
>
>
> --
> View this message in context: http://r-sig-geo.2731867.n2.nabble.com/summing-rasters-with-a-condition-given-by-other-rasters-tp7588222p7588226.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