R:沿时间线计算每个单元格中的皮尔逊相关系数
我有两套光栅,都有相同的x,y,z范围。我做了两层:斯塔克A和斯塔克B。我想计算沿时间线的两个堆栈之间的每个网格单元中的皮尔逊相关系数()。我做了一个更简单的例子(请原谅我用愚蠢的方式创建光栅)R:沿时间线计算每个单元格中的皮尔逊相关系数,r,raster,pearson,R,Raster,Pearson,我有两套光栅,都有相同的x,y,z范围。我做了两层:斯塔克A和斯塔克B。我想计算沿时间线的两个堆栈之间的每个网格单元中的皮尔逊相关系数()。我做了一个更简单的例子(请原谅我用愚蠢的方式创建光栅) a1我编辑了Paulo推荐的在计算中处理NAs的方法,它似乎在一系列测试中工作得很快,包括上面的数据集: stack.correlation <- function(stack1, stack2, cor.method){ # output template cor.map <- r
a1我编辑了Paulo推荐的在计算中处理NAs的方法,它似乎在一系列测试中工作得很快,包括上面的数据集:
stack.correlation <- function(stack1, stack2, cor.method){
# output template
cor.map <- raster(stack1)
# combine stacks
T12 <- stack(stack1,stack2)
rnlayers=nlayers(T12)
# the function takes a vector, partitions it in half, then correlates
# the two sections, returning the correlation coefficient.
stack.sequence.cor <- function(myvec,na.rm=T){
myvecT1<-myvec[1:(length(myvec)/2)]
myvecT2<-myvec[(length(myvec)/2+1):length(myvec)]
return(cor(myvecT1,myvecT2, method = cor.method, use="complete.obs"))
}
# apply the function above to each cell and write the correlation
# coefficient to the output template.
cor.map <- stackApply(T12, indices = rep(1, rnlayers),
fun = stack.sequence.cor, na.rm = FALSE)
return(cor.map)
}
cor_r=stack.correlation(stacka, stackb, "pearson")
stack.correlation更简单的方法:
library(raster)
a1 <- raster(matrix(c(1,1,1,1,1,1,1,1,NA),3,3))
a2 <- raster(matrix(c(2,2,2,2,1,2,2,NA,2), 3, 3))
a3 <- raster(matrix(c(3,3,3,3,3,2,NA,3,3), 3, 3))
b1 <- raster(matrix(c(2,2,2,2,2,2,2,2,2), 3, 3))
b2 <- raster(matrix(c(3,3,3,3,3,3,3,3,3), 3, 3))
b3 <- raster(matrix(c(4,4,4,4,4,4,4,4,4), 3, 3))
sa <- stack(a1, a2, a3)
sb <- stack(b1, b2, b3)
funcal <- function(xy) {
xy <- na.omit(matrix(xy, ncol=2))
if (ncol(xy) < 2) {
NA
} else {
cor(xy[, 1], xy[, 2])
}
}
s <- stack(sa, sb)
calc(s, funcal)
库(光栅)
a1两件事:(a)不,这使得帮助非常困难,(b)is.na==FALSE
不起作用(试试看),esa[!is.na(esa)]可能是你想要的。@EDU你尝试过像@PauloCardoso这样的东西吗?这是正确的方向,但它也不处理NAs。卢卡斯下面的修改非常有效。非常感谢!好极了我一直在琢磨保罗的方法,因为它也不处理NAs。你修改过的版本很有魅力!
library(raster)
a1 <- raster(matrix(c(1,1,1,1,1,1,1,1,NA),3,3))
a2 <- raster(matrix(c(2,2,2,2,1,2,2,NA,2), 3, 3))
a3 <- raster(matrix(c(3,3,3,3,3,2,NA,3,3), 3, 3))
b1 <- raster(matrix(c(2,2,2,2,2,2,2,2,2), 3, 3))
b2 <- raster(matrix(c(3,3,3,3,3,3,3,3,3), 3, 3))
b3 <- raster(matrix(c(4,4,4,4,4,4,4,4,4), 3, 3))
sa <- stack(a1, a2, a3)
sb <- stack(b1, b2, b3)
funcal <- function(xy) {
xy <- na.omit(matrix(xy, ncol=2))
if (ncol(xy) < 2) {
NA
} else {
cor(xy[, 1], xy[, 2])
}
}
s <- stack(sa, sb)
calc(s, funcal)