0

I would like to try to avoid stating which variables to assess by instead relying on the suffix _num. mutating a variable conditional on a variable name is possible, but this code needs updating because it should now use across.

df %<>% mutate(`Manipulation1` = case_when(
A1_num > 2 ~ "support",
B1_num > 2 ~ "support",
C1_num > 2 ~ "support",
A4_num > 2 ~ "support",
B4_num > 2 ~ "support",
C4_num > 2 ~ "support",
same 6 variables == 2 ~ "neither", 
same 6 variables < 2 ~ "reject",
TRUE~ NA_character_))

This answer using contains doesn't work for this scenario because it is evaluating responses in a column, not the variable name.

ibm
  • 744
  • 7
  • 14
  • There are some logic missing. Does it looks for all columns to match or a single column – akrun Jul 25 '21 at 23:06
  • For all columns, each of the (6 _num) column values can be > 2, == 2 or <2 – ibm Jul 25 '21 at 23:08
  • I meant that `if_any` checks whether a row from one of the column is greater than 2, or ==2 or <2. If you need condition that says all the column sshould be >2, then change `if_any` or `if_all`. Without an example, it is diffiuclt to know your expected – akrun Jul 25 '21 at 23:10
  • 1
    `if_any` was enough for my purposes, I didn't need `all_of` but it is great to learn about these less used selector helpers, and the whole `mutate`, then `case_when`, then NULL the mutates. – ibm Jul 27 '21 at 16:32

1 Answers1

3

We could wrap with if_any

library(dplyr)
library(stringr)
nm1 <- str_c(LETTERS[1:3], rep(c(1, 4), each = 3), "_num")
df <- df %>%
      mutate(s1 = if_any(all_of(nm1), ~ . > 2),
             n1 = if_any(all_of(nm1), ~ . == 2),
             r1 = if_any(all_of(nm1), ~ . < 2),
             Manipulation1 = case_when(s1 ~ "support",
                                      n1 ~ "neither",
                                      r1 ~ "reject",
                            TRUE ~ NA_character_),
                     s1 = NULL, n1 = NULL, r1 = NULL)
akrun
  • 874,273
  • 37
  • 540
  • 662