【问题标题】:Raster linear and conditional regression using raster stacks by month in R在 R 中按月使用栅格堆栈进行栅格线性和条件回归
【发布时间】:2016-10-05 10:00:14
【问题描述】:

我有两个栅格堆栈,我想进行回归分析。如果每个堆栈中的每个栅格都是一年中的一个月(6 个数据点将是两年中的三个月,即两个不同年份的一月、二月和三月),我如何使用索引计算斜率,以便结果生成 3坡度栅格(每个月一个)好吗?

#First raster track
r <- raster(ncol=10, nrow=10)
r[]=1:ncell(r)
S <- stack(r,r,r,r,r,r)

#Second raster stack
r1 <- raster(ncol=10, nrow=10)
r1[]=1:ncell(r1)
N <- stack(r1,r1,r1,r1,r1,r1)

#combine both raster stacks
s <- stack(S,N)

#function to calculate slope
fun=function(x) { if (is.na(x[1])){ NA } else { lm(x[7:12] ~ x[1:6] )$coefficients [2]}}

#apply function
slope <- calc(s, fun)

结果应该是 3 个栅格。

第二个问题: 如果我想使用第三个栅格堆栈进行条件回归,代码会是什么?

【问题讨论】:

    标签: r date linear-regression indices r-raster


    【解决方案1】:

    试试1:12的乐趣

    fun(1:12)
    
    # Error in model.frame.default(formula = x[6:12] ~ x[1:6], drop.unused.levels = TRUE) : 
    #  variable lengths differ (found for 'x[1:6]')
    

    应该是

    fun=function(x) { if (is.na(x[1])){ NA } else { lm(x[7:12] ~ x[1:6] )$coefficients [2]}}
    

    工作示例

    library(raster)
    r <- raster(ncol=10, nrow=10)
    set.seed(99)
    s <- stack(sapply(1:12, function(i) setValues(r, runif(ncell(r)))))
    
    fun <- function(x) { if (is.na(x[1])){ NA } else { lm(x[7:12] ~ x[1:6] )$coefficients [2]}}
    
    slope <- calc(s, fun)
    

    对于三个斜坡:

    fun3 <- function(x) {
        r <- rep(NA, 3)
        if (!is.na(x[1])) {
           r[1] <- lm(x[3:4] ~ x[1:2] )$coefficients[2]
           r[2] <- lm(x[7:8] ~ x[5:6] )$coefficients[2]
           r[3] <- lm(x[11:12] ~ x[9:10] )$coefficients[2]
        }
        r
     }
    
    slope3 <- calc(s, fun3)
    

    【讨论】:

    • 感谢@RobertH 的更正。关于如何按指数或按月进行回归的任何想法?
    猜你喜欢
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2014-11-01
    • 2018-10-06
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多