r - 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))
但由于某种原因,它不起作用。谢谢你的帮助!
解决方案
您可以首先使用以下方法建立第一对零件的索引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
推荐阅读
- c++ - 没有 constexpr 的前向声明 - 原因是什么?
- aem - AEM版本升级后组件操作不正确
- javascript - Markdown 文件无法与 js 库一起正常工作,换行问题
- elasticsearch - 了解通过滚动查询或时间点 API 保持打开的 Elasticsearch 搜索上下文的开销
- flutter - 如何在颤动中删除文本字段光标气泡
- javascript - 我的 javascript 库无法处理所有文档元素(调用 js 库问题之前和之后)
- amcharts4 - 如何显示线系列圆形项目符号与Amcharts 4相交的所有工具提示文本?
- r - 尝试在 R 中应用创建的函数
- java - 主题:Android Firebase 中的查询——数据检索
- c# - C# 如何知道如何正确修改命名空间以使其工作?