Home > Blockchain >  R: Unexpected behaviour in ifelse
R: Unexpected behaviour in ifelse

Time:09-16

I would like to understand why this (to me) unexpected behaviour is happening, because I do not understand the logic behind. This is a perfectly reproducible example.

Let's start with two different vectors:

comp1 <- c(90,2,113,123,99,203,1,137,1,140,44)
action <- c(2,1,1)

Now, I want to do a simple ifelse check and if it is false, I want to delete the first row, and if I simply do this, it works fine:

action <- action[2:length(action)]

> action
[1] 1 1

This is exactly right and this is what I want. Now, if I use the ifelse function with a false boolean like this:

action <- ifelse(any(49==comp1), 2, action[2:length(action)])

I am telling it if TRUE to put put a 2 in action and if FALSE to do the previous operation action[2:length(action)]. Now, as you can see the default condition in this case is FALSE, as there is no 49 in the comp1 vector from above, and I would be expecting, as before, 1 1 vector as a result. However, the result is unexpected:

> action
[1] 1

Following other threads such as this I also tried using %in% with the same outcome.

> action <- ifelse(49 %in% comp1, 2, action[2:length(action)])
> action
[1] 1

Does anybody have any idea why this is happening?

Thanks in advance!

CodePudding user response:

Use if/else instead of ifelse as ifelse requires all arguments to be of same length. The first argument 'test' is of length 1, 'yes' 1 whereas 'no' is of different length. According to ?ifelse

If yes or no are too short, their elements are recycled. yes will be evaluated if and only if any element of test is true, and analogously for no.

if(49 %in% comp1) 2 else action[2:length(action)]
[1] 1 1
  • Related