С case_when
, используйте any
.
library(dplyr)
df %>%
group_by(group) %>%
mutate(new_agreement = case_when(
any(agreement == 'bad') ~ 'inconsistent',
TRUE ~ 'consistent'))
## A tibble: 10 x 5
## Groups: group [2]
# group piece answer agreement new_agreement
# <fct> <fct> <fct> <fct> <chr>
# 1 group1 A noise good inconsistent
# 2 group1 A silence good inconsistent
# 3 group1 A silence good inconsistent
# 4 group1 B silence bad inconsistent
# 5 group1 B loud_noise bad inconsistent
# 6 group1 B noise bad inconsistent
# 7 group1 B loud_noise bad inconsistent
# 8 group1 B noise bad inconsistent
# 9 group2 C silence good consistent
#10 group2 C silence good consistent
Данные в формате dput
.
df <-
structure(list(group = structure(c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L), .Label = c("group1", "group2"),
class = "factor"), piece = structure(c(1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 3L, 3L), .Label = c("A", "B", "C"),
class = "factor"), answer = structure(c(2L, 3L, 3L,
3L, 1L, 2L, 1L, 2L, 3L, 3L), .Label = c("loud_noise",
"noise", "silence"), class = "factor"), agreement =
structure(c(2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L),
.Label = c("bad", "good"), class = "factor")),
class = "data.frame", row.names = c(NA, -10L))