2
votes

I tried looking for an answer for this question but I'm not sure if I'm asking the question correctly in the search bar, so here it goes. I would like to create an if or ifelse statement with a logical condition based on two vectors.

Here's a shortened version of the code:

ifelse(Vector1 == c(T,T,T),"Combo1","Combo2")

I created a vector called "Vector1". Its value is currently [T T F]. So in the case above, I would like an output value of "Combo2" to be printed. Instead, I am getting a vector of [Combo1 Combo1 Combo2]. So I see that it is passing those values into a vector, but I would like the ifelse statement to pass a single TRUE or FALSE value to get a single "Combo" value.

There are 8 combinations of [T/F T/F T/F], so I'm trying to nest several of these ifelse statements together, but I figured I'd start simple.

I tried using the if statement as well, but that didn't seem to work for me either.

I appreciate any help.

1
From ?ifelse: "returns a value with the same shape as test". That's why you get a vector returned with the same shape as Vector1. - neilfws
Except 'test' is a logical vector. So it's not the same shape of Vector1 ... it's the same shape as Vector1 == c(T,T,T) and the "shape" that is #[1] TRUE TRUE FALSE. (Admittedly, the test for a logical vector each being true will be the vector itself, but the 'test' object is not jsut Vector1 but rather the results from the == operator. - IRTFM

1 Answers

7
votes

You can also do a normal if statement, since it returns a value:

my_result = if(all(Vector1 == c(T,T,T))) {"Combo1"} else {"Combo2"}

The ifelse function is made for vectorized conditional statements.

By using the standard if statement, you remove potential ambiguity/misinterpretation because the standard if only evaluates one condition.