如何将回归摘要(例如p值和系数)输出到rasterbrick中?
我正在使用R执行回归。我成功地将r平方的残余标准误差提取到一个光栅砖中。然后我需要运行另一个代码来获得p值(F stat)。我如何将fun1和fun2结合起来,以便一次生成包含这些信息的光栅砖 这是我的密码:如何将回归摘要(例如p值和系数)输出到rasterbrick中?,r,regression,lm,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(nc
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创建测试数据
我想我得到了答案
在cbind()中再添加几列将允许我在输出光栅堆栈中添加更多层
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
库(光栅)
#1创建测试数据
你的文字写的是p值,标题写的是系数。哪一个?谢谢@Roman Lustrik。编辑了我的标题和帖子。我当时很忙,把事情搞混了。抱歉。为什么不保留一个同时返回resid.s.e
和pf
的函数,然后选择变量传递到calc
?重新计算相同的lm
似乎又是多余的。是的,你是对的@zx8754。我以前就是想不出怎么做。我想我现在找到了答案。