Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

r - dplyr mutate ifelse returning first value of group instead of by-row

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use if and else instead of ifelse():

df %>% 
 group_by(grp) %>%
 mutate(value2 = if(all(value1 == 0)) 0 else value2)

  grp   value1 value2
  <fct>  <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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...