本文介绍了从分组数据中选择第一行和最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题
使用 dplyr ,如何选择顶部和底部一个声明中的观察数据/分组数据行?
Using dplyr, how do I select the top and bottom observations/rows of grouped data in one statement?
数据和例如
给定数据框
df <- data.frame(id=c(1,1,1,2,2,2,3,3,3), stopId=c("a","b","c","a","b","c","a","b","c"), stopSequence=c(1,2,3,3,1,4,3,1,2))我可以使用 slice获得每个组的顶部和底部观察结果,但使用两个单独的数据:
I can get the top and bottom observations from each group using slice, but using two separate statments:
firstStop <- df %>% group_by(id) %>% arrange(stopSequence) %>% slice(1) %>% ungroup lastStop <- df %>% group_by(id) %>% arrange(stopSequence) %>% slice(n()) %>% ungroup我可以将这两个统计信息合并成一个选择 的顶部和底部观察结果吗? / p>
Can I combine these two statmenets into one that selects both top and bottom observations?
推荐答案可能有一个更快的方法:
There is probably a faster way:
df %>% group_by(id) %>% arrange(stopSequence) %>% filter(row_number()==1 | row_number()==n())更多推荐
从分组数据中选择第一行和最后一行
发布评论