1

As with many things in R, there are multiple ways to test whether set of criteria contains desired values. I am looking for suggestions to reduce the amount of code indicated below. The desired result is provided

library(dplyr)
df.test=data.frame(
  L=c("A","B","C"),
  num=c(1,2,3),
  num2=c(1,2,3)
)

what works, but a little cumbersome.


myfun.=function(L){
     case_when(
        L == "A" | L ==  "B" | L ==  "C"  ~ 1 # this is the conditional statement i am seeking to reduce
      )
  }

apply function

df.test %>% mutate(
  +     result=myfun.(L)
  +    )

desired output

L num num2 result
1 A   1    1      1
2 B   2    2      1
3 C   3    3      1

what i have tried but doesn't work.

l=list(c("A","B","C"))

myfun.=function(L){
  case_when(
    L == all( L %in% l)  ~ 1
  )
}

i looked at several sources including the 'Hands on Programing Guide with R' (pp. 131 ) and the following post Boolean operators && and || and wasnt able to find a simpler solution.

akrun
  • 874,273
  • 37
  • 540
  • 662
cn838
  • 69
  • 8

1 Answers1

2

Just use %in% instead of ==

library(dplyr)
df.test %>% 
     mutate(result =  +(L %in% c("A", "B", "C")))

-output

 L num num2 result
1 A   1    1      1
2 B   2    2      1
3 C   3    3      1
akrun
  • 874,273
  • 37
  • 540
  • 662