Home > Enterprise >  How to make conditional replacement more efficient in R?
How to make conditional replacement more efficient in R?

Time:11-30

I replaced multiple variables into the new variable using case_when, but I noticed there is a lot of repeated code and I wonder if there is a more efficient way of doing this. Basically I want to avoid writing col_a == "" every time

tt <- df1%>%
  mutate(col_a = case_when(
      col_a == "GK" ~ "Goalkeeper",

      col_a == "RB" |
      col_a == "LB" |
      col_a == "RWB" |
      col_a == "LWB" ~ "Side Back",

      col_a == "LCB" |
      col_a == "CB"|
      col_a == "RCB" ~ "C Defender",

      TRUE ~ col_a))

Thanks,

CodePudding user response:

Use %in% -

library(dplyr)

tt <- df1%>%
  mutate(col_a = case_when(
    col_a == "GK" ~ "Goalkeeper",
    col_a %in% c("RB","LB","RWB","LWB") ~ "Side Back",
    col_a %in%  c("LCB", "CB", "RCB") ~ "C Defender",
    TRUE ~ col_a))
  • Related