简体   繁体   中英

How to extract regression coefficients from rasterstack in R?

I am trying to fit a sine curve to a datasets and derived the coefficients. As this is my first time dealing with rasterstack, I am not sure how to print the coefficients. Does it possible to represent the coeff in term of raster layer?

library(raster)
r <- raster(nrow=5, ncol=5) 
s <- stack( sapply(1:20, function(i) setValues(r, rnorm(ncell(r), i, 3) )) ) 
s[1] <- NA 

time <- 1:nlayers(s) 

fun1 <- function(x) {
if (is.na(x[1])) {
NA
} else {
xcost<-cos(2*pi*time/24)
xsine<-sin(2*pi*time/24)
m = lm(x~xcost+xsine)
m$coefficients[2]
}
}

e1 <- calc(s, fun1)

Thanks in advance.

> e1[1,1]

NA 
> e1[1,2]

-1.810707 
> as.matrix(e1)
           [,1]      [,2]      [,3]      [,4]       [,5]
[1,]         NA -1.810707 -1.619409 -1.862829 -0.8928249
[2,] -4.4466952 -2.763915 -1.095858 -1.513916 -3.2462229
[3,] -0.5758164 -5.258762 -3.567696 -3.051799 -2.6290404
[4,] -2.9026886 -3.929019 -1.832168 -1.308834 -3.4590392
[5,] -3.6900736 -1.223912 -4.581699 -2.188620 -3.8804321

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM