R create multiple variables with one condition

Viewed 99

Is there a simpler way to write it,create multiple variables for one condition? like this

  if am == 1 then do;
    a="";
    b="";
    c=;
  end;
  else if am == 0 then do;
    ...
  end;

The following is the R code I wrote

library(dplyr)
dt1 <- mtcars
dt2 <- dt1 %>% 
mutate(a = case_when(am == 1 ~ "a1",
                     am == 0 ~ "a2",
                     am == 2 ~ "a3"),

       b = case_when(am == 1 ~ "a2",
                     am == 0 ~ "a2",
                     am == 2 ~ "a2"),

       c = case_when(am == 1 ~ 0,
                     am == 0 ~ 1,
                     am == 2 ~ 2))
1 Answers
lookup <- data.frame(
  am = c(1, 0, 2), a = c('a1', 'a2', 'a3'), b = 'a2', c = c(0, 1, 2)
)
left_join(dt1, lookup, 'am') 
Related