简体   繁体   English

if_else 和 case_when 与 group_by 之间的行为差​​异

[英]Difference in behavior between if_else and case_when with group_by

I can't figure out why these two are not behaving in the same way.我不明白为什么这两个人的行为方式不同。 The case_when one works as I expect it to, while if_else one gives the error: case_when一个按我的预期工作,而if_else一个给出错误:

Error: `true` must be length 1 (length of `condition`), not 2 
Run `rlang::last_error()` to see where the error occurred.

The example code:示例代码:

tb <-
  tibble(DC = c(1, 1, 2), ID = c(1, 1, 2), V = c(100, 200, 400)) %>% 
  group_by(DC, ID)

tb %>%
  mutate(V = if_else(sum(V) == 300, V / n(), 1))

tb %>% 
  mutate(V = case_when(sum(V) == 300 ~ V / n(), TRUE ~ 1))

Thanks in advance.提前致谢。

That is because true and false values in if_else should be of same length as condition .这是因为if_else truefalse值应该与condition长度相同。 Here, condition is of length 1 ( sum(V) == 300 ) whereas true value for 1st group is of length 2 ( V / n() ) hence, the error.这里, condition的长度为 1( sum(V) == 300 ),而第 1 组的true值长度为 2( V / n() ),因此,错误。

Since this is a scalar comparison you can use if / else instead.由于这是一个标量比较,您可以使用if / else代替。

library(dplyr)

tb %>% mutate(V = if(sum(V) == 300) V / n() else 1)

#    DC    ID     V
#  <dbl> <dbl> <dbl>
#1     1     1    50
#2     1     1   100
#3     2     2     1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM