简体   繁体   English

如何根据另一列中较大的值过滤行?

[英]How to filter rows according to the bigger value in another column?

I have a data frame like below我有一个如下所示的数据框

d1<-c('a','b','c','d','e','f','g','h','i','j','k','l')

d2<-c(1,5,1,2,13,2,32,2,1,2,4,5)

df1<-data.frame(d1,d2)

Which looks like the data table in this picture看起来像这张图片中的数据表

在此处输入图像描述

My goal is to filter the rows based on which value of d2 in every 3 rows is biggest.我的目标是根据每 3 行中 d2 的哪个值最大来过滤行。 So it would look like this:所以它看起来像这样: 在此处输入图像描述 Thank you!谢谢!

We may use rollmax from zoo to filter the rows我们可以使用zoorollmaxfilter

library(dplyr)
library(zoo)
df1 %>% 
  filter(d2 == na.locf0(rollmax(d2, k = 3, fill = NA)))
  d1 d2
1  b  5
2  e 13
3  g 32
4  l  5

You can create a grouping variable that puts observations into groups of 3. I have first created a sequence from 1 to the total number of rows, incremented by 3. And then repeated each number of this sequence 3 times and subset the result to get a vector the same length of the data, incase the number of observations is not perfectly divisible by 3. Then simply filter rows based by the largest number of each group in d2 column.您可以创建一个分组变量,将观察值分成 3 个组。我首先创建了一个从 1 到总行数的序列,递增 3。然后将该序列的每个数字重复 3 次并将结果子集得到一个向量相同长度的数据,以防观察的数量不能完全被 3 整除。然后只需根据 d2 列中每个组的最大数量过滤行。

library(dplyr)

df1 %>%
  mutate(group = rep(seq(1, n(), by = 3), each = 3)[1:n()]) %>% 
  group_by(group) %>% 
  filter(d2 == max(d2))

# A tibble: 4 x 3
# Groups:   group [4]
#  d1       d2 group
#  <chr> <dbl> <dbl>
# 1 b         5     1
# 2 e        13     4
# 3 g        32     7
# 4 l         5    10

Yet another solution:另一个解决方案:

library(tidyverse)

d1<-c('a','b','c','d','e','f','g','h','i','j','k','l')
d2<-c(1,5,1,2,13,2,32,2,1,2,4,5)

df1<-data.frame(d1,d2)

df1 %>% 
  mutate(id = rep(1:(n()/3), each=3)) %>% 
  group_by(id) %>% 
  slice_max(d2) %>% 
  ungroup %>% select(-id)

#> # A tibble: 4 × 2
#>   d1       d2
#>   <chr> <dbl>
#> 1 b         5
#> 2 e        13
#> 3 g        32
#> 4 l         5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM