Tidyverse question: Select only rows that contain certain values

50 Views Asked by At

I have a survey question that has multiple choice answers. I created a new column for each answer where the values are 1 if they selected it, 0 if they didn't. The problem is that I am trying to create a dplyr chart where I separate out the answers between those that only responded one choice, vs others that answered a combo of choices. My current code is this:

emotion_chart <- df %>% select(emotions_angry, emotions_anxious, emotions_nervous, emotions_stressed, emotions_normal, emotions_happy)

I've selected the columns that I need to analyze, where the values are 0s and 1s (see picture). However, I want to first make a new variable that includes cases OF survey respondents that chose ONLY normal but nothing else. Then, step 2 will be creating a new variable that selects respondents that said they felt normal and a negative emotion (for example, someone who said they felt "normal" AND " stressed" and "anxious"). I hope this makes sense and any help will be sincerely appreciated.

2

There are 2 best solutions below

0
Eduardo López On

You could use an ifelse statement:

ifelse(emotions_normal == 1 and {the rest} == 0, 1, 0)

And so on.

0
Baraliuh On

I must say the question is vague/hard to understand and has no example data. Consider having small example data and a desired output to get more efficient help. Still, here is my take on it:

For step one you could do:

df %>% 
    # Filter all rows with more than one answer
    filter(rowSums(across(contains('emotions'))) != 1)

Select only normal could be:

df %>% 
    # Filter all rows with only normal answer
    filter(as.logical(emotions_normal) & rowSums(across(-emotions_normal)) == 0)