Search code examples
rcasepastemutate

Mutate, case_when, paste in R


apple banana orange fruits_name
1 0 1 apple orange
1 0 0 apple
1 0 1 apple orange
1 1 1 apple banana orange

I want to create and mutate the column "frutis_name" if the rest of the columns get 1. As an example, apple and orange got 1 then "frutis_name will be apple space banana.


Solution

  • Perhaps not the easiest solution but one that works, based on the idea of recasting column names as values, which is done by pivot_longer:

    library(tidyverse)
    df %>%
      # create row ID:
      mutate(row = row_number()) %>%
      # cast longer so that fruit names become values:
      pivot_longer(-row, names_to = "fruits") %>%
      # for each combination of `row` and `value`...
      group_by(row, value) %>%
      # ... combine fruit names if `value == 1`:
      mutate(fruits = ifelse(value == 1, str_c(fruits, collapse = " "), fruits)) %>%
      # remove obsolete rows:
      filter(value == 1 & !duplicated(fruits)) %>%
      # deactivate grouping:
      ungroup() %>%
      # remove unnecessary columns:
      select(-c(value, row)) %>%
      # bind original `df` together with new `fruit` column:
      bind_cols(df, .)
      apple banana orange              fruits
    1     1      0      1        apple orange
    2     1      0      0               apple
    3     1      0      1        apple orange
    4     1      1      1 apple banana orange