3

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}
1
  • I'm actually not able to understand your actual purpose of efficient way. But one obvious optimization is to execute a=0 b=0 c=0 above if so that you can avoid last else part. Commented Jan 4, 2018 at 23:44

1 Answer 1

3

Define a function and use it three times:

cond <- function(x, x1, x2) 
  case_when(
     x > 10 ~ x1,
     x >  5 ~ x2,
     TRUE ~ 0)

df %>% mutate(a = cond(x, 1, 11), b = cond(x, 2, 12), c = cond(x, 3, 13))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.