筛选每个组的中间行 [英] Filter the middle row of each group
本文介绍了筛选每个组的中间行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
df <- data.frame(id=c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3),
x=c(1,2,3,3,5,1,4,3,1,2,8,9,3,1,0))
对于每个组,如果我想过滤第一行
For each group, if I want to filter the first row
df %>%
group_by(id) %>%
filter(row_number()==1)
如果必须过滤最中间的行怎么办?
What do I do if I have to filter the most middle row?
推荐答案
n()/ 2
将 nrow
个组,个上限
对奇数值取小数。
n()/2
halves the nrow
of the group, ceiling
rounds up decimals for odd values.
df %>%
group_by(id) %>%
filter(row_number()==ceiling(n()/2))
# A tibble: 3 x 2
# Groups: id [3]
id x
<dbl> <dbl>
1 1 3
2 2 3
3 3 3
这篇关于筛选每个组的中间行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文