获取 R 中每组的最后一行 [英] Get last row of each group in R

查看:30
本文介绍了获取 R 中每组的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些结构类似于的数据:

I have some data similar in structure to:

a <- data.frame("ID" = c("A", "A", "B", "B", "C", "C"),
                "NUM" = c(1, 2, 4, 3, 6, 9),
                "VAL" = c(1, 0, 1, 0, 1, 0))

我正在尝试按 IDNUM 对其进行排序,然后获取最后一行.此代码用于获取最后一行并将其汇总为唯一 ID,但是,它实际上并没有像我想要的那样获取完整的最后一行.

And I am trying to sort it by ID and NUM then get the last row. This code works to get the last row and summarize down to a unique ID, however, it doesn't actually get the full last row like I want.

a <- a %>% arrange(ID, NUM) %>%
  group_by(ID) %>%
  summarise(max(NUM))

我明白为什么这段代码不起作用,但我正在寻找 dplyr 获取每个唯一 ID

I understand why this code doesn't work but am looking for the dplyr way of getting the last row for each unique ID

预期结果:

  ID        NUM     VAL
  <fct    <dbl>    <dbl>
1 A           2       0
2 B           4       1
3 C           9       0

注意:我承认虽然它几乎是 从分组数据中选择第一行和最后一行,该线程上的答案并不是我想要的.

Note: I will admit that though it is nearly a duplicate of Select first and last row from grouped data, the answers on that thread were not quite what I was looking for.

推荐答案

你可以试试:

a %>% 
  group_by(ID) %>% 
  arrange(NUM) %>%  
  slice(n())

这篇关于获取 R 中每组的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆