 # If statement and storage

Hello House,
Good day.
Please I have problem with the short code below and needs advice/direction accordingly. I have an input data (X) ranging from 2 to 40 at 2.5 interval. The length of X and Z datasets are 16. I am writing a conditional statement such that: for i = 1, Z[i] > 0, X =X[i] and for Z[i] = 0, X = 0.. Please note that i =1:16. The values of X and Z are found below:

``````
X =  seq(2, 40, 2.5)
Z = c(2, 1, 0, 4, 1, 1, 3, 0, 8, 1, 21, 0, 10, 0, 1, 5)

X <- matrix(X, nrow = length(X), byrow = TRUE)

Z <- matrix(Z, nrow = length(Z), byrow = TRUE)

length(X)
length(Z)

d = NULL
df = NULL

for (i in 1:length(X)){

p = X[i]
r = Z[i]

p
r

temporary_function <- function(r) {

if (r > 0){
(p)
}
else {
(0)
}
}
}
mapply(FUN = temporary_function, X)

``````

Hi @Zakky,
If I understand your question, you want to update X[i] to 0 every time the corresponding Z[i] == 0, otherwise leave X[i] as is. Is this correct? Secondly, is using loops and mapply a requirement?

The easiest and fastest approach is to take advantages of R's vectorization.

You can test the equality of Z == 0, which returns a logical vector/matrix
where the condition is either true or false.

`````` Z == 0

[,1]
[1,] FALSE
[2,] FALSE
[3,]  TRUE
[4,] FALSE
[5,] FALSE
[6,] FALSE
[7,] FALSE
[8,]  TRUE
[9,] FALSE
[10,] FALSE
[11,] FALSE
[12,]  TRUE
[13,] FALSE
[14,]  TRUE
[15,] FALSE
[16,] FALSE`
``````

From here, you can use this test of equality as a way to index the positions of X and update
it where the Z == 0 is TRUE.

``````X[Z == 0] <- 0
``````

giving

``````X
[,1]
[1,]  2.0
[2,]  4.5
[3,]  0.0
[4,]  9.5
[5,] 12.0
[6,] 14.5
[7,] 17.0
[8,]  0.0
[9,] 22.0
[10,] 24.5
[11,] 27.0
[12,]  0.0
[13,] 32.0
[14,]  0.0
[15,] 37.0
[16,] 39.5``````

Hello, sorry for my late response.

you want to update X[i] to 0 every time the corresponding Z[i] == 0, otherwise leave X[i] as is. Is this correct? YES PLS

Secondly, is using loops and mapply a requirement? NOT REALLY.

I got ur suggestion and it works out for me. Thank you so much.

If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.