![](/img/trans.png)
[英]Filter in group_by + mutate not working as in group_by + summarise in dplyr R
[英]R dplyr conditional mutate with group_by
我有一个分组的 data.frame 并且想要有条件地检查某个列的all()
一列。
在这个例子中,我有一个包含 3 列的简单 data.frame; 我按列code
分组,如果该组的B
列完全是NA
,我想从A
列复制值,否则保留B
的原始非NA
值。
输入:
> example <- tibble::tribble(
~code, ~A, ~B,
"1", 0.5, 0.7,
"1", 0.5, 0.3,
"1", 0.5, 0.25,
"2", 0.2, NA,
"2", 0.8, NA,
"2", 0.5, NA
)
> example %>% dplyr::group_by(code)
# A tibble: 6 x 3
# Groups: code [2]
code A B
<chr> <dbl> <dbl>
1 1 0.5 0.7
2 1 0.5 0.3
3 1 0.5 0.25
4 2 0.2 NA
5 2 0.8 NA
6 2 0.5 NA
期望的输出:
# A tibble: 6 x 3
code A B
<chr> <dbl> <dbl>
1 1 0.5 0.7
2 1 0.5 0.3
3 1 0.5 0.25
4 2 0.2 0.2
5 2 0.8 0.8
6 2 0.5 0.5
我试过使用ifelse()
并且它可以检查all(is.na(B))
但它不会将 rowwise 属性作为标准行为,而只是从第一个值复制。
example %>%
dplyr::group_by(code) %>%
dplyr::mutate(
B = ifelse(all(is.na(B)), A, B)
)
# A tibble: 6 x 3
# Groups: code [2]
code A B
<chr> <dbl> <dbl>
1 1 0.5 0.7
2 1 0.5 0.7
3 1 0.5 0.7
4 2 0.2 0.2
5 2 0.8 0.2
6 2 0.5 0.2
归属固定值是可以的。
example %>%
dplyr::group_by(code) %>%
dplyr::mutate(
isBna = ifelse(all(is.na(B)), 'y', 'n')
)
# A tibble: 6 x 4
# Groups: code [2]
code A B isBna
<chr> <dbl> <dbl> <chr>
1 1 0.5 0.7 n
2 1 0.5 0.3 n
3 1 0.5 0.25 n
4 2 0.2 NA y
5 2 0.8 NA y
6 2 0.5 NA y
并且使用dplyr::if_else()
它会抛出一个错误,指出A
和B
不是固定值。
example %>%
dplyr::group_by(code) %>%
dplyr::mutate(
B = if_else(all(is.na(B)), A, B)
)
Error: Problem with `mutate()` input `B`.
x `true` must be length 1 (length of `condition`), not 3.
ℹ Input `B` is `if_else(all(is.na(B)), A, B)`.
ℹ The error occurred in group 1: code = "1".
Run `rlang::last_error()` to see where the error occurred.
我的真实案例错误几乎没有什么不同。
# sometime like this
Error: Problem with `mutate()` input `xx`.
x `false` must be a logical vector, not a double vector.
# and sometimes like this
Error: Problem with `mutate()` input `xx`.
x `false` must be length 1 (length of `condition`), not 12.
有什么办法可以在管道链中实现我的目标%>%
吗?
提前致谢。
代替ifelse
使用if
/ else
因为all
返回长度为 1 的输出,并且ifelse
将返回与输入长度相同的输出,因此它会在整个组中回收第一个元素。
library(dplyr)
example %>%
group_by(code) %>%
mutate(B = if(all(is.na(B))) A else B))
# code A B
# <chr> <dbl> <dbl>
#1 1 0.5 0.7
#2 1 0.5 0.3
#3 1 0.5 0.25
#4 2 0.2 0.2
#5 2 0.8 0.8
#6 2 0.5 0.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.