title: Create new column based on counting non-NA values across multiple columns
body: <p>I have a data frame of questionnaire data in a wide format. For some questions, respondents are asked to answer whether a given scenario applies to them (Yes, No). If the scenario applies to them, respondents are asked to provide examples of the scenarios (in some cases, there might be more than one example).</p>
  
  <p>My dataset looks something like the following, with Q1 referring to a scenario, while Q1a, Q1b, and Q1c are open-ended fields for them to provide examples of said scenario.</p>
  
  <pre><code>df &lt;- data.frame(Q1 = c("Yes", "No", "Yes", "No", "Yes", "Yes", "Yes"), 
               Q1a = c("AAA", NA, "AAA", NA, "ABC", "DDD", "EEE"),
               Q1b = c("BBB", NA, NA, NA, "BCD", NA, "AAA"),
               Q1c = c(NA, NA, NA, NA, "EFG", NA, "AAA"))
  </code></pre>
  
  <p>I want to create a new column such that, if a scenario applies to the respondent,  it will count, for a given row, and across the 3 columns (Q1a, Q1b, Q1c), the number of examples the respondents provided.</p>
  
  <p>What I have come up so far is to hardcode every permutation of non-NA values:</p>
  
  <pre><code>df$count_non_NA &lt;- ifelse(df$Q1 == "No", 0,
                        ifelse(df$Q1 == "Yes" &amp; !is.na(df$Q1a) &amp; !is.na(df$Q1b) &amp; !is.na(df$Q1c), 3,
                               ifelse(df$Q1 == "Yes" &amp; ((!is.na(df$Q1a) &amp; !is.na(df$Q1b)) | 
                                        (!is.na(df$Q1b) &amp; !is.na(df$Q1c))|
                                        (!is.na(df$Q1a) &amp; !is.na(df$Q1c))), 2, 1)))
  </code></pre>
  
  <p>It works, but I am going to repeat the same thing for every single scenario. Furthermore, I am curious what will happen if respondents are provided with more than 3 examples to fill in. It would be a pain to hardcode the permutations. Hence, I am seeking a more efficient solution to my problem.</p>
  
  <p><a href="https://i.stack.imgur.com/5Bf9L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Bf9L.png" alt="Count non-NA values across columns"></a></p>
  
  <p>The screenshot above shows the result of my code. To illustrate, row 1 shows that the scenario applies to them, and two examples are provided ("AAA" in Q1a column; "BBB" in Q1b column). As Q1a and Q1b are non-NA columns, the count_non_NA column reflects a 2.</p>