[R-sig-Geo] focal {raster} fun = freq(): Error in (function (classes, fdef, mtable) : unable to find an inherited method for function 'freq' for signature '"numeric"' [large rasters]
Sandra MacFadyen
sandramf at live.co.za
Sun Jun 15 13:33:50 CEST 2014
Dear R-sig-Geo'ers,
I am trying the calculate different focal measures of diversity on a raster
without using execGRASS.
My code (see below) works fine on small (ras1) and large (ras2) rasters.
However, when I try to parse these as functions to focal {raster} to
calculate over "moving window" values within a neighbourhood, I get an error
when using freq(): Error in (function (classes, fdef, mtable) : unable to
find an inherited method for function 'freq' for signature '"numeric"'.
I would appreciate any advice you could give.
Thank you
Regards
Sandra
# Create matrix
seq1 <- seq(1:9)
mat1 <- matrix(seq1, 3)
# change values
mat1[2,2]=2
mat1[3,3]=2
# convert to raster
ras1 = raster(mat1)
# Calculate diversity measures
(richness <- length(unique(ras1)) ) # Richness
(eveness <- richness / ncell(ras1) ) # Eveness
(Ni <- freq(ras1)[,2] ) # Frequency of individuals
(Pi <- freq(ras1)[,2]/ncell(ras1) ) # Proportion of individuals
(f.simpD <- (freq(ras1)[,2]/ncell(ras1))^2 ) # Value to calc Simpson index
(simpD <- sum((freq(ras1)[,2]/ncell(ras1))^2) ) # Simpson index
# Do the same thing but with a large raster
# Create large matrix
seq2 <- runif(1000000, -120, 4980)
mat2 <- matrix(seq2, 1000)
# convert to raster
ras2 = raster(mat2)
# Calculate diversity measures
(richness <- length(unique(ras2)) ) # Richness
(eveness <- richness / ncell(ras2) ) # Eveness
(Ni <- freq(ras2)[,2] ) # Frequency of individuals
(Pi <- freq(ras2)[,2]/ncell(ras2) ) # Proportion of individuals
(f.simpD <- (freq(ras2)[,2]/ncell(ras2))^2 ) # Value to calc Simpson index
(simpD <- sum((freq(ras2)[,2]/ncell(ras2))^2) ) # Simpson index
# Now with Focal functions (moving windows)
# Define custom functions
# Set functions to calculate diversity indices
f.rich = function(x) { length(unique(x)) }
f.even = function(x) { length(unique(x))/ ncell(x) }
f.Ni = function(x) { freq(x)[,2] }
f.1simpD = function(x) { (freq(x)[,2]/ncell(x))^2 }
f.2simpD = function(x) { sum((freq(x)[,2]/ncell(x))^2) }
#Pass function to focal function 5x5
lsat.rich <- focal(lsat, w=matrix(1/25,nrow=5,ncol=5), fun=f.rich)
lsat.even <- focal(lsat, w=matrix(1/25,nrow=5,ncol=5), fun=f.even)
lsat.Ni <- focal(lsat, w=matrix(1/25,nrow=5,ncol=5), fun=f.Ni)
More information about the R-sig-Geo
mailing list