gpt4 book ai didi

r - Dplyr 对分组数据同时按值过滤顶行和底行

转载 作者:行者123 更新时间:2023-12-01 22:33:34 25 4
gpt4 key购买 nike

# Sample dataframe
set.seed(123)
d = data.frame(x = runif(120), grp = gl(3, 40))

# Select top_n
d %>%
group_by(grp) %>%
top_n(n=3, wt=x)

如何在同一管道内选择顶部和底部观测值?已尝试以下方法但不起作用

# helper function
my_top_bott = function(x, n, wt) {
x1 = x %>% top_n(n=n, wt=wt)
x2 = x %>% top_n(n=n, wt=-wt)
x = bind_rows(x1, x2)
return(x)
}

# Pipe
d %>%
group_by(grp) %>%
my_top_bott(., n=3, wt=x)

最佳答案

一种可能性是:

d %>%
group_by(grp) %>%
filter(dense_rank(x) <= 3 | dense_rank(desc(x)) <= 3)

x grp
<dbl> <fct>
1 0.0456 1
2 0.957 1
3 0.0421 1
4 0.994 1
5 0.963 1
6 0.0246 1
7 0.858 2
8 0.0458 2
9 0.895 2
10 0.0948 2
11 0.815 2
12 0.000625 2
13 0.103 3
14 0.985 3
15 0.0936 3
16 0.954 3
17 0.0607 3
18 0.954 3

或者@IceCreamToucan提出的可能性:

d %>%
group_by(grp) %>%
filter(!between(dense_rank(x), 3 + 1, n() - 3))

或者涉及match()的可能性:

d %>%
group_by(grp) %>%
filter(!is.na(x[match(x, sort(x)[c(1:3, (n()-2):n())])]))

关于r - Dplyr 对分组数据同时按值过滤顶行和底行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56809476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com