如何从分组数据框中的每个组中获取第n个元素 [英] How to get every nth element from each group in a grouped data frame

查看:48
本文介绍了如何从分组数据框中的每个组中获取第n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大数据框,其中有一列,具有一个组名,该组名与 dplyr 分组.因此,多行具有相同的组名.为了减少数据,我想从每个组的第一个元素开始提取第n个元素.有没有 R方式而没有循环?

I have a big data frame with a column, with a group name, which is grouped with dplyr. So multiple rows have the same group name. To reduce the data, I would like to extract every nth element starting from the first element from each group. Is there any R way without loops?

用序列对每一行进行子集化,存在经常丢失每个组的第一行的问题.例如

Subsetting every row with a sequence, has the problem that often the first row of each group is missed. e.g.

data[seq(1, nrow(data), 10), ] # Some groups start without the first row.

输入:

   Val Group
1  1.0 Fruit
2  2.0 Fruit
3  3.0 Fruit
4  1.5 Veg
5  2.8 Veg
6  4.2 Veg
7  5.1 Veg

输出(第二个元素,请注意第三行!):

Output (every second element, be aware of 3rd row!):

   Val Group
1  1.0 Fruit
2  3.0 Fruit
**3  1.5 Veg**
4  4.2 Veg

推荐答案

library(dplyr)
data %>% group_by(Group) %>%
  slice(seq(1, n(), by = 2))

这给出了:

# A tibble: 4 x 2
# Groups:   Group [2]
    Val Group
  <dbl> <fct>
1   1   Fruit
2   3   Fruit
3   1.5 Veg  
4   4.2 Veg 

这篇关于如何从分组数据框中的每个组中获取第n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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