1
我有一個柵格堆棧,需要用其他堆棧中的圖層替換它包含的某些圖層。R:使用第二個柵格堆棧中的圖層替換柵格堆棧中的多個圖層
我想解決方案非常簡單直接,但到目前爲止我無法找到它。
給你重複的例子,這裏是我試圖做:
library(raster)
# create some raster
r1 <- raster(nrows=10, ncols=10, xmn=0, xmx=10, ymn = 0, ymx = 10)
r1[] <- sample(1:100, 100, replace = TRUE)
r2 <- raster(nrows=10, ncols=10, xmn=0, xmx=10, ymn = 0, ymx = 10)
r2[] <- sample(1:100, 100, replace = TRUE)
r3 <- raster(nrows=10, ncols=10, xmn=0, xmx=10, ymn = 0, ymx = 10)
r3[] <- sample(1:100, 100, replace = TRUE)
r4<- raster(nrows=10, ncols=10, xmn=0, xmx=10, ymn = 0, ymx = 10)
r4[] <- sample(1:100, 100, replace = TRUE)
# put the raster into a stack
r_stack <- stack(r1, r2, r3, r4)
#calculate the mean of the raster
r_mean <- mean(r_stack)
# What I would like to do is to subtract the mean from some of the
# raster in the stack (layers_to_replace), but not from all, and to
# replace the raster in the stack with the new difference.
# For example I would like to replace the second and fourth layer with
# the difference.
l_replace <- c(2, 4)
# Note: I place the difference into a second stack for the sake
# of the example as my original data comes in a second stack
rep_stack <- r_stack[[l_replace]] - r_mean
r_stack[[l_replace]] <- rep_stack
不幸的是這種方法是行不通的,並引發以下錯誤:
Error in v[] <- value : incompatible types (from S4 to logical) in subassignment type fix
In addition: Warning messages:
1: In if (i < 1) { : the condition has length > 1 and only the first element will be used
2: In if (i > nl + 1) { : the condition has length > 1 and only the first element will be used
3: In if (i > nl) { : the condition has length > 1 and only the first element will be used
如何任何想法要解決這個問題將更受歡迎。
簡單,工作液由此接受的答案。 – Improbability