title: How to check for the existence of a certain value in a set of variables only when there is no NA?
body: <p>I have a dataframe with over hundreds of variables, grouped in different factors (&quot;Happy_&quot;,&quot;Sad_&quot;, etc) and I want to create a set new variables indicating whether a participant put a rating of 4 in any of the variables in one factor. However, if any of the variable in that factor is NA, then the new variable will also output NA.</p>
  <p>I have tried the following, but it didn't work:</p>
  <pre><code>library(tidyverse)
  df &lt;- data.frame(Subj = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;),
                   Happy_1_Num = c(4,2,2,NA),
                   Happy_2_Num = c(4,2,2,1),
                   Happy_3_Num = c(1,NA,2,4),
                   Sad_1_Num = c(2,1,4,3),
                   Sad_2_Num = c(NA,1,2,4),
                   Sad_3_Num = c(4,2,2,1))
  
  # Don't work
  df &lt;- df %&gt;% mutate(Happy_Any4 = ifelse(if_any(matches(&quot;^Happy_&quot;) &amp; matches(&quot;_Num$&quot;), ~ is.na(.)), NA,
                                                                   ifelse(if_any(matches(&quot;^Happy_&quot;) &amp; matches(&quot;_Num$&quot;), ~ . == 4),1,0)),
                      Sad_Any4 = ifelse(if_any(matches(&quot;^Sad_&quot;) &amp; matches(&quot;_Num$&quot;), ~ is.na(.)), NA,
                                        ifelse(if_any(matches(&quot;^Sad_&quot;) &amp; matches(&quot;_Num$&quot;), ~ . == 4),1,0)))
  </code></pre>
  <p>I tried a workaround by first generating a set of variables to indicate if that factor has any NA, and after that check if participant put any rating of &quot;4&quot;. it works; but since I have many factors, I was wondering if there is a more elegant way of doing it.</p>
  <pre><code># workaround
  df &lt;- df %&gt;% mutate(
    NA_Happy = ifelse(if_any(matches(&quot;^Happy_&quot;) &amp; matches(&quot;_Num$&quot;), ~ is.na(.)), 1,0),
    NA_Sad = ifelse(if_any(matches(&quot;^Sad_&quot;) &amp; matches(&quot;_Num$&quot;), ~ is.na(.)), 1,0))
  
  df &lt;- df %&gt;% mutate(
    Happy_Any4 = ifelse(NA_Happy == 1, NA,
                          ifelse(if_any(matches(&quot;^Happy_&quot;) &amp; matches(&quot;_Num$&quot;), ~ . == 4),1,0)),
    Sad_Any4 = ifelse(NA_Sad == 1, NA,
                          ifelse(if_any(matches(&quot;^Sad_&quot;) &amp; matches(&quot;_Num$&quot;), ~ . == 4),1,0)))
  </code></pre>