[R-sig-Geo] Error message in calc()

GD grothered at gmail.com
Mon Oct 7 13:06:44 CEST 2013


Apologies the last suggestion was totally wrong, since 'calc' applies the
function to each cell (represented as a vector).

However, the problem might be that the 'which' function inside your 'fun1'
is sometimes returning more than one value. In that case, you might try
forcing 'w' to have the same length every time. See the following code:
 
> library(raster)
Loading required package: sp
> 
> # Original function
> fun1 <- function(x){
+           m <- max(x)
+           w <- which(x==m)
+           return(c(m,w))
+           } 
> 
> # Function that only outputs the first element of 'w', and also gives the
> length of w
> fun2 <- function(x){
+           m <- max(x)
+           w <- which(x==m)
+           return(c(m,w[1],length(w)))
+           } 
> 
> # A stack
> slogo <- stack(system.file("external/rlogo.grd", package="raster")) 
> 
> s2 <- calc(slogo, fun = fun1) # This fails
Error in .local(x, values, ...) : 
  values must be numeric, integer or logical.
> 
> 
> s3 <- calc(slogo, fun = fun2) # This works -- and note that length(w) is
> not constant
> s3
class       : RasterBrick 
dimensions  : 77, 101, 7777, 3  (nrow, ncol, ncell, nlayers)
resolution  : 1, 1  (x, y)
extent      : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=merc 
data source : in memory
names       : layer.1, layer.2, layer.3 
min values  :       0,       1,       1 
max values  :     255,       3,       3 





--
View this message in context: http://r-sig-geo.2731867.n2.nabble.com/Error-message-in-calc-tp7584795p7584798.html
Sent from the R-sig-geo mailing list archive at Nabble.com.



More information about the R-sig-Geo mailing list