Home > other >  case_when function to satisfy all exact constraints
case_when function to satisfy all exact constraints

Time:11-04

I'm working with the case_when() function in R because I'm handling all exceptions in a certain piece of code. My question is rather simple I think, but I'm not sure how to achieve it. With the case_when() function multiple arguments (like in any other statement) can be taken into account. Given the following example;

a <- "aap"

b <- case_when(str_count(a,"a") > 1 ~ 1,
               str_count(a,"a") > 1 & str_count(a,"p") >= 1 ~ 2)

I want to return the value 2, but because the argument of return value 1 is also satisfied, it returns 1 instead of 2. Is there an easy workaround for this? Kind regards

CodePudding user response:

You could invert your conditions. Also, here your second condition is not satisfied (there is one p in aap, not >1). If you type :

b <- case_when(str_count(a,"a") > 1 & str_count(a,"p") >= 1 ~ 2,str_count(a,"a") > 1 ~ 1)

It indeed returns 2.

CodePudding user response:

case_when stops at the first TRUE condition. This is also why an else condition (or "default", if you will) occurs lastly:

case_when(
  a ~ 'a is true and nothing else matters',
  b ~ 'a was not true, but b is, and nothing else matters',
  TRUE ~ 'none of the above was true'
)

Swap the two statements and you should be good.

  • Related