如何将回归汇总(例如p值和coeff)输出到栅格砖中?

时间:2013-11-28 10:03:29

标签: r regression lm

我正在使用R来执行回归。我成功地将r平方残差标准误差提取到栅格砖中。然后我需要运行另一个代码来获得p值(F stat)。我如何组合fun1和fun2,以便我可以一次性生成包含这些信息的栅格砖?

这是我的代码:

library(raster)

#1 create test data
 r <- raster(nrow=10, ncol=10)
 set.seed(0)
 s <- stack(lapply(1:12, function(i) setValues(r, rnorm(ncell(r), i, 3) )))
 time <- 1:nlayers(s)
 s[1:5] <- NA

#2 Run function1 to obtain r-squared and residual standard error
 fun1 <- function(x) {
 if (all(is.na(x))) {
 return(cbind(NA,NA))
 }
 m = lm(x~time)
 s  <- summary(m)
 r2 <- s$r.squared
 resid.s.e <- s$sigma
 cbind(r2, resid.s.e)
 }

#3 Run function to obtaion p-value(from F stat)
 fun2 <- function(x) {
 if (all(is.na(x))) {
 return(cbind(NA,NA))
 }
 m = lm(x~time)
 s  <- summary(m)
 r2 <- s$r.squared
 pf<- pf(s$fstatistic[1], s$fstatistic[2], s$fstatistic[3],lower.tail = FALSE) 
 cbind(r2, pf)
 }

#Apply both functions with rasterstack and plot
 r <- calc(s, fun)
 plot(r)

 r2 <- calc(s, fun2)
 plot(r2)

提前致谢。

1 个答案:

答案 0 :(得分:2)

我想我得到了答案。

在cbind()中添加更多列将允许我在输出rasterstack中添加更多图层。

library(raster)

#1 create test data
  r <- raster(nrow=10, ncol=10)
  set.seed(0)
  s <- stack(lapply(1:12, function(i) setValues(r, rnorm(ncell(r), i, 3) )))
  time <- 1:nlayers(s)
  s[1:5] <- NA

#2 Run function1 to obtain r-squared, residual standard error and p-value(F stat)
  fun <- function(x) {
  if (all(is.na(x))) {
  return(cbind(NA,NA,NA))
  }
  m = lm(x~time)
  s  <- summary(m)
  r2 <- s$r.squared
  resid.s.e <- s$sigma
  pf<- pf(s$fstatistic[1], s$fstatistic[2], s$fstatistic[3],lower.tail = FALSE) 
  cbind(r2, resid.s.e, pf)
  }

  r <- calc(s, fun)
  r
   class       : RasterBrick 
   dimensions  : 10, 10, 100, 3  (nrow, ncol, ncell, nlayers)
   resolution  : 36, 18  (x, y)
   extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
   coord. ref. : +proj=longlat +datum=WGS84 
   data source : in memory
   names       :      layer.1,      layer.2,      layer.3 
   min values  : 1.300285e-01, 1.457297e+00, 5.199987e-07 
   max values  :    0.9271788,    5.0219805,    0.2495312