我有一个栅格堆栈,我想通过规范原始图层中的每一层来创建一个新的堆栈。我可以在下面的例子中做到这一点。有没有更简单的方法?
library(raster)
#> Loading required package: sp
set.seed(1)
# Create random data for 3 layers in a stack
s <- stack(raster(matrix(rnorm(100, mean = 10, sd = 1), nrow = 10)),
raster(matrix(rnorm(100, mean = 20, sd = 3), nrow = 10)),
raster(matrix(rnorm(100, mean = 30, sd = 5), nrow = 10)))
# Roll my own functions for normalizing
mu <- function (x) {
mean(extract(x, 1:ncell(x)))
}
sigma <- function (x) {
sd(extract(x, 1:ncell(x)))
}
normalize <- function (x) {
return((x - mu(x))/sigma(x))
}
normalize_stack <- function (x) {
ls <- list()
for (i in 1:dim(x)[3]) {
ls[[i]] <- normalize(subset(x, i))
}
return(stack(ls))
}
# Normalize the stack
normal <- normalize_stack(s)
# Verify that means are essentially 0
for (i in 1:dim(normal)[3]) {
print(mu(subset(normal, i)))
}
#> [1] 7.222304e-16
#> [1] -2.867314e-16
#> [1] -1.519569e-16
# Verify that sds are 1
for (i in 1:dim(normal)[3]) {
print(sigma(subset(normal, i)))
}
#> [1] 1
#> [1] 1
#> [1] 1
由reprex package(v0.3.0)于2019-10-16创建
答案 0 :(得分:2)
由于您已经在使用offerName
软件包,因此一种方法是使用raster
本身,如下所示:
您的示例数据:
raster::scale
使用规模的简单方法:
library(raster)
#> Loading required package: sp
set.seed(1)
# Create random data for 3 layers in a stack
s <- stack(raster(matrix(rnorm(100, mean = 10, sd = 1), nrow = 10)),
raster(matrix(rnorm(100, mean = 20, sd = 3), nrow = 10)),
raster(matrix(rnorm(100, mean = 30, sd = 5), nrow = 10)))
答案 1 :(得分:1)
一个简单的更改是转储mu
,sigma
和normalize
并仅使用scale
:
normalize_stack <- function (x) {
ls <- list()
for (i in 1:dim(x)[3]) {
ls[[i]] <- scale(subset(x, i))
}
return(stack(ls))
}