2017-04-27 8 views
1

ラスタスタックがあり、レイヤの一部を別のスタックのレイヤに置き換える必要があります。R:ラスタスタック内の複数のレイヤを2番目のラスタスタックのレイヤに置き換えます。

解決方法はかなりシンプルで簡単ですが、これまで私はそれを見つけることができませんでした。ここで、あなたに再現可能な例を与えることを

は私がしようとしたものです:どのように上の任意のアイデアを

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 

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 

残念ながら、このアプローチは動作し、次のエラーをスローしません。この問題を解決することは大歓迎以上のことです。

答えて

0

これは動作するはずです:

for(ind in seq(along = l_replace)) r_stack[[l_replace[ind]]][] <- rep_stack[[ind]][] 

r_stack 
class  : RasterStack 
dimensions : 10, 10, 100, 4 (nrow, ncol, ncell, nlayers) 
resolution : 1, 1 (x, y) 
extent  : 0, 10, 0, 10 (xmin, xmax, ymin, ymax) 
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
names  : layer.1, layer.2, layer.3, layer.4 
min values : 1.00, -54.25, 2.00, -54.25 
max values : 100.0, 51.5, 100.0, 51.5 

また、何とか読みやすくするために:

for(ind in seq(along = l_replace)){ 
    setValues(r_stack, getValues(rep_stack[[ind]]), layer = l_replace[ind]) 
} 
+0

簡単で、作業溶液ので、答えとして受け入れました。 – Improbability

関連する問題