I am trying to create multiple variables based on a condition using R dplyr. I have to write the same condition three times to get this work but I am guessing that there is an efficient way to do this task by writing the condition once and using that condition to create multiple variables. The reason I am trying to do this is, if there is a change in the condition, it will be easier to update the condition at one single location instead of updating it three times. Please help.
Example:
Current solution:
library(dplyr)
x = c(12,8,3)
df<-data.frame(x)
y<- df %>% mutate( a = ifelse(x>10 ,1,
ifelse(x>5 ,11,0)),
b = ifelse(x>10 ,2,
ifelse(x>5 ,12,0)),
c = ifelse(x>10 ,3,
ifelse(x>5 ,13,0))
)
Looking for something like this:
if x>10 then
{a=1 b=2 c=3}
else if x>5 then
{a=11 b=12 c=13}
else
{a=0 b=0 c=0}
a=0 b=0 c=0aboveifso that you can avoid lastelsepart.