[R-sig-Geo] Problems with NA values and lm() in calc() in raster package

Lars Dalby lars.dalby at gmail.com
Wed Apr 11 14:56:22 CEST 2012


Dear list

I am trying to do a linear regression of the values in a brick with time
using the calc function in the raster package.

In some of my raster layers in the brick I have NA values and this causes
problems.

Any hints on how to work around this?

require(raster)
# From help to calc function
# create data
r <- raster(nrow=10, ncol=10)
s1 <- s2<- list()
for (i in 1:12) {
	s1[i] <- setValues(r, rnorm(ncell(r), i, 3) )
	s2[i] <- setValues(r, rnorm(ncell(r), i, 3) )
}
s1 <- stack(s1)
s2 <- stack(s2)
s <- stack(s1, s2)
# regression of values in one brick (or stack) with 'time'
time <- 1:nlayers(s)
fun <- function(x) { lm(x ~ time)$coefficients[2] }
x2 <- calc(s, fun)
# This runs fine.

# Now if I introduce a cell with only NA values in the stack:
s[1] <- NA
x3 <- calc(s, fun) # returns an error: Error in .calcTest(x[1:5], fun,
na.rm, forcefun, forceapply) : cannot use this function

# Setting na.option = na.exclude in the function:
fun2 <- function(x) { lm(x ~ time, na.option = na.exclude)$coefficients[2] } 
x4 <- calc(s, fun2) # same error as above

s <- stack(s1, s2) # resetting the stack
r <- raster(nrow=10, ncol=10)
r <- setValues(r, rnorm(ncell(r), 1, 3) )
r[1] <- NA
s <- stack(s, r) # Now only one of the rasters has a NA value
time <- nlayers(s) 
x5 <- calc(s, fun) # Same error message
x6 <- calc(s, fun2) # Same error message

sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] RColorBrewer_1.0-5 raster_1.9-82      sp_0.9-98         

loaded via a namespace (and not attached):
[1] grid_2.15.0    lattice_0.20-6 tools_2.15.0

Best regards
Lars

Lars Dalby
Msc. PhD student
Ecoinformatics & Biodiversity
Department of Bioscience, Aarhus University
Denmark

--
View this message in context: http://r-sig-geo.2731867.n2.nabble.com/Problems-with-NA-values-and-lm-in-calc-in-raster-package-tp7455990p7455990.html
Sent from the R-sig-geo mailing list archive at Nabble.com.



More information about the R-sig-Geo mailing list