Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional replacement of values in an array

Tags:

r

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

like image 554
Augusto Avatar asked Jun 13 '26 14:06

Augusto


2 Answers

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!

like image 90
JayCe Avatar answered Jun 15 '26 05:06

JayCe


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]
  })
like image 41
R. Schifini Avatar answered Jun 15 '26 03:06

R. Schifini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!