[英]select entire (but filtered) column in rowwise calculation (Dplyr)
以下基本计算的正确 Dplyr 管道是什么?
dat <- data.frame(a = 0:10, b = 0:10, c = 0:10)
dat$d <- apply(dat, 1, sum)
ind <- dat$d>quantile(dat$d[dat$d>0], 0.1)
我试过(但失败了):
ind <- tibble(dat) %>% rowwise() %>%
mutate(d = sum(c_across(a:c)), ind = d>quantile(select_var(d>0), 0.1)) %>%
pull(ind)
tibble(dat) %>%
rowwise() %>%
mutate(
d = sum(c(a, b, c)),
ind = d > quantile(dat %>% filter(d >0) %>% pull(d), 0.1)
) %>%
pull(ind)
给出与您的ind
相同的值。 轻微的困难是由于您正在根据数据框的子集而不是其整体来计算分位数。
您可以使用.$
执行此操作,以便为整个数据返回quantile
dat %>% rowwise() %>%
mutate(d = sum(c_across(a:c))) %>%
mutate(ind = d > quantile(.$d[.$d >0], 0.1))
a b c d ind
1 0 0 0 0 FALSE
2 1 1 1 3 FALSE
3 2 2 2 6 TRUE
4 3 3 3 9 TRUE
5 4 4 4 12 TRUE
6 5 5 5 15 TRUE
7 6 6 6 18 TRUE
8 7 7 7 21 TRUE
9 8 8 8 24 TRUE
10 9 9 9 27 TRUE
11 10 10 10 30 TRUE
检查是否在d
之前不添加.$
会得到不希望的结果
dat %>% rowwise() %>%
mutate(d = sum(c_across(a:c))) %>%
mutate(ind = d > quantile(d[d >0], 0.1))
# A tibble: 11 x 5
# Rowwise:
a b c d ind
<int> <int> <int> <int> <lgl>
1 0 0 0 0 NA
2 1 1 1 3 FALSE
3 2 2 2 6 FALSE
4 3 3 3 9 FALSE
5 4 4 4 12 FALSE
6 5 5 5 15 FALSE
7 6 6 6 18 FALSE
8 7 7 7 21 FALSE
9 8 8 8 24 FALSE
10 9 9 9 27 FALSE
11 10 10 10 30 FALSE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.