Search code examples
rif-statementmutateacross

mutate across columns with ifelse


I'm trying to mutate values across multiple columns to values from another column.

This is my dataset:

library(stringr)
library(dplyr)
library(fastDummies)

score <- sample(1:100,20,replace=TRUE)
df <- data.frame(score)

df <- df %>%
   mutate(grp = cut(score, breaks = c(-Inf, seq(0, 100, by = 20), Inf)), 
      grp = str_c("G", as.integer(droplevels(grp)), '_', 
      str_replace(grp, '\\((\\d+),(\\d+)\\]', 
     '\\1_\\2'))) %>% 
   dummy_cols("grp", remove_selected_columns = TRUE) %>% 
   rename_with(~ str_remove(.x, 'grp_'), starts_with('grp_'))

I want to mutate columns that start with the letter "G", so G1_0_20, G2_20_40, etc.

If columns that start with G (G1_0_20, G2_20_40,etc) has value of 1, then its value should match column "Score", otherwise NA.

I can't quite figure out how to use mutate across with ifelse statement.

I would appreciate all the help there is! Thanks!!!


Solution

  • I think this is it:

    df %>%
      mutate(across(starts_with("G"), ~ifelse(. == 1, score, NA)))
       score G1_0_20 G2_20_40 G3_40_60 G4_60_80 G5_80_100
    1     52      NA       NA       52       NA        NA
    2     90      NA       NA       NA       NA        90
    3     73      NA       NA       NA       73        NA
    4     11      11       NA       NA       NA        NA
    5     16      16       NA       NA       NA        NA
    6     47      NA       NA       47       NA        NA
    7     42      NA       NA       42       NA        NA
    8     62      NA       NA       NA       62        NA
    9     64      NA       NA       NA       64        NA
    10    25      NA       25       NA       NA        NA
    11    47      NA       NA       47       NA        NA
    12    63      NA       NA       NA       63        NA
    13    96      NA       NA       NA       NA        96
    14    95      NA       NA       NA       NA        95
    15     3       3       NA       NA       NA        NA
    16    25      NA       25       NA       NA        NA
    17    78      NA       NA       NA       78        NA
    18    10      10       NA       NA       NA        NA
    19    51      NA       NA       51       NA        NA
    20    12      12       NA       NA       NA        NA