I want to modify an array but with an element-by-element condition. This is what I want to do
vector <- runif(18, 0,1)
xx <- array(vector, dim=c(2,3,3))
for (i in 1:2) {
for (j in 1:3) {
xx[i,j,1] <- ifelse(xx[i,j,1]<0.5,1,xx[i,j,1])
xx[i,j,2] <- ifelse(xx[i,j,2]<0.4,1.5,xx[i,j,2])
xx[i,j,3] <- ifelse(xx[i,j,3]<0.2,2,xx[i,j,3])
}
}
Is there a more efficient way to do it? Thanks
Not sure what you mean by efficient but this avoids looping:
vector <- runif(18, 0,1)
xx <- array(vector, dim=c(2,3,3))
xx
xx[,,1][xx[,,1]<.5] <- 1
xx[,,2][xx[,,2]<.4] <- 1.5
xx[,,3][xx[,,3]<.2] <- 2
Try it online!
There are two ways that you could simplify this double loop
Option 1:
vector <- runif(18, 0,1)
xx <- array(vector, dim=c(2,3,3))
xx[,,1][xx[,,1]<.5] = 1
xx[,,2][xx[,,2]<.4] = 1.5
xx[,,3][xx[,,3]<.2] = 2
You still have to write one line for each condition, though.
The second way is to use lapply, but in this case you have to create three vectors: index, threshhold, substitution
idx = 1:3
thr = c(.5, .4, .2)
sb = c(1, 1.5, 2)
lapply(idx, function(k){
xx[,,k][ xx[,,k]< thr[x] ] <<- sb[k]
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With