I'm looking to write a conditional statement using ifelse, that will evaluate 3 conditions on 3 vectors simultaneously. If either of the conditions are true, along the vectors, I like to add a constant to all three vectors.
Here is an example dataset:
a<-c(rep(0,5),rep(1,2))
b<-c(rep(0,6),rep(1,1))
c<-rep(5,7)
(data <- cbind(a,b,c))
a b c
[1,] 0 0 5
[2,] 0 0 5
[3,] 0 0 5
[4,] 0 0 5
[5,] 0 0 5
[6,] 1 0 5
[7,] 1 1 5
For each row, if a, b, or c is zero, I would like to add a constant k = 0.5 to the values.
Here is my expected dataset after the conditional statement:
k <- 0.5
exp.a exp.b exp.c
[1,] 0.5 0.5 5.5
[2,] 0.5 0.5 5.5
[3,] 0.5 0.5 5.5
[4,] 0.5 0.5 5.5
[5,] 0.5 0.5 5.5
[6,] 1.5 0.5 5.5
[7,] 1.0 1.0 5.0
I tried something along the lines of:
(exp.a <- (a + ifelse((a == 0), k, 0)))
The code above does not evaluate vectors b and c if they are zero, so it is not what I'm looking for. How may I write the ifelse statement so that all 3 vectors will be evaluated if the value at each row is zero, and if any of them is zero, add a constant k to all values in the row?
Thanks!
Aucun commentaire:
Enregistrer un commentaire