New column based on combination of two columns

I would like to add a new column in my dataset, based on two other columns.

I know I can achieve this task by hard-coding all combinations myself, for instance like this:

mtcars %>%
  rowwise() %>% 
  mutate(Comb = case_when(vs == 0 & am == 0 ~ 0,
                          vs == 1 & am == 0 ~ 1,
                          vs == 0 & am == 1 ~ 2,
                          vs == 1 & am == 1 ~ 3))

Is there any tidyverse function I could use instead? With only 4 combinations I can hard-code it, but with more it becomes impossible.

library(dplyr)
(a1 <- mtcars |>
  rowwise() |>
  mutate(Comb = case_when(vs == 0 & am == 0 ~ 0,
                          vs == 1 & am == 0 ~ 1,
                          vs == 0 & am == 1 ~ 2,
                          vs == 1 & am == 1 ~ 3)) |>
    ungroup() |> 
  select(vs,am,Comb) )

(b2 <- mtcars |>
  mutate(Comb = as.integer(interaction(vs,am))-1) |> 
  select(vs,am,Comb) |> tibble())

identical(a1,b2)
1 Like

Perfect, exactly what I wanted!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.