首页 > 解决方案 > R:根据一列中的条件过滤行

问题描述

我有一个数据框:

a<-c(1,1,1,1,1,1,1,1,1,1,1)
b<-c(100,100,100,100,100,100,100,100,100,100,100)
c<-c(1,3,1,1,3,1,1,3,1,1,3)
d<-c(3400,3403,3407,3408,3412,3423,3434,3436,3445,3454,3645)
df<-data.frame(d,b,c,a)
df
      d   b c a
1  3400 100 1 1
2  3403 100 3 1
3  3407 100 1 1
4  3408 100 1 1
5  3412 100 3 1
6  3423 100 1 1
7  3434 100 1 1
8  3436 100 3 1
9  3445 100 1 1
10 3454 100 1 1
11 3645 100 3 1

并且我想始终过滤一个满足以下条件的行对:第一行的 c 列值必须为 3,第二行的 c 列值必须为 1,并且该对之间的列 d 值必须为 < 10. 所以这个例子中的预期输出应该是:

      d   b c a
2  3403 100 3 1
3  3407 100 1 1
8  3436 100 3 1
9  3445 100 1 1

我尝试了以下方法:

filter(df,first(c)==3,nth(c,2)==1,any(diff(d) < 10))

但由于某种原因,它不起作用。谢谢你的帮助!

标签: rfilterconditional-statements

解决方案


您可以首先使用以下方法建立第一对零件的索引which

library(dplyr)
inds <- which(df$c == 3 & lead(df$c) == 1 & lead(df$d) - df$d < 10)

然后在索引1 上对您的数据框进行子集化:

df[sort(unique(c(inds, inds + 1))),]
     d   b c a
2 3403 100 3 1
3 3407 100 1 1
8 3436 100 3 1
9 3445 100 1 1

或者,您可以执行以下操作:

library(dplyr)
df1 <- df %>%                                        # get the first row
  filter(c == 3 & lead(c) == 1 & lead(d) - d < 10) 
df2 <- df %>%                                        # get the second row
  filter(lag(c) == 3 & c == 1 & d - lag(d) < 10)
arrange(rbind(df1, df2), d)                          # bind the two together and arange by d

推荐阅读