从分组数据中选择第一行和最后一行

编程入门 行业动态 更新时间:2024-10-26 23:25:41
本文介绍了从分组数据中选择第一行和最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

问题

使用 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())

更多推荐

从分组数据中选择第一行和最后一行

本文发布于:2023-07-09 00:22:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1082139.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!