I would like to fill a column conditionally using dplyr::mutate. One level of the new variable should correspond to if a value was present at all in the previous column and the other level is an 'else' condition.
I have a dataframe:
group piece answer agreement
group1 A noise good
group1 A silence good
group1 A silence good
group1 B silence bad
group1 B loud_noise bad
group1 B noise bad
group1 B loud_noise bad
group1 B noise bad
group2 C silence good
group2 C silence good
I want to create a new variable grouping by group where if 'bad' appears in 'agreement', then the value should be 'inconsistent' but if all of the values of 'agreement' are 'good', then the value should be 'consistent.'
group piece answer agreement new_agreement
group1 A noise good bad
group1 A silence good bad
group1 A silence good bad
group1 B silence bad bad
group1 B loud_noise bad bad
group1 B noise bad bad
group1 B loud_noise bad bad
group1 B noise bad bad
group2 C silence good good
group2 C silence good good
But case_when doesn't quite do that - it's just copying the same variable over again:
newdf <- df %>%
group_by(group) %>%
mutate(new_agreement = case_when(agreement == 'bad' ~
"inconsistent", agreement =='good' ~ "consistent")) %>%
as.data.frame()