I'm trying to mutate a data.frame using ifelse:
df = data.frame(grp = c('a', 'a', 'a', 'b', 'b', 'b'),
value1 = c(0, 0, 0, 0, 1, 2),
value2 = 1:6)
df %>%
group_by(grp) %>%
mutate(value2 = ifelse(all(value1 == 0), 0, value2))
which returns
# # A tibble: 6 x 3
# # Groups: grp [2]
# grp value1 value2
# <chr> <dbl> <dbl>
# 1 a 0 0
# 2 a 0 0
# 3 a 0 0
# 4 b 0 4
# 5 b 1 4
# 6 b 2 4
instead of
# # A tibble: 6 x 3
# # Groups: grp [2]
# grp value1 value2
# <chr> <dbl> <dbl>
# 1 a 0 0
# 2 a 0 0
# 3 a 0 0
# 4 b 0 4
# 5 b 1 5
# 6 b 2 6
How can I change the mutate
so that the rows of "value2" are unchanged if the condition is false?
question from:
https://stackoverflow.com/questions/65921987/dplyr-mutate-ifelse-returning-first-value-of-group-instead-of-by-row 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…