在R数据帧中查找列值遵循序列的行 [英] Finding rows in R dataframe where a column value follows a sequence
问题描述
我有一个下面的数据框,它是一个分类器的输出。
I have a dataframe as below which is an output of a classifier.
col1, class
123, 2
122, 5
124, 7
125, 9
126, 15
127, 2
128, 19
129, 5
130, 7
179, 9
180, 3
我想找到具有某种类型的行的行,例如所有行的类都在seq 5,7,9
。
I want to find the rows that has a certain pattern of class, like all rows whose classes are in seq 5,7,9
.
我想出的解决方案是通过移动一行并比较列如下
The solution I came up with is pasting class columns by shifting one row and comparing columns as below
col1, class, class1, class2
123, 2,5,7
122, 5,7,9
124, 7,9,15
125, 9,15,2
126, 15,2,19
127, 2,19,5
128, 19,5,7
129, 5,7,9
130, 7,9,3
179, 9,3,NA,
180, 3,NA,NA
只有我的图案中的字段数量相同,这样才能解决,但是我的会改变。一些模式甚至可以是5到7个字段。
This solves only if my number of fields in the patter is same, but mine will change. Some patterns could even 5 to 7 fields.
推荐答案
我们可以从数据中使用
,然后 shift
.table 粘贴
元素在一起,检查我们在哪里 579
We can use shift
from data.table
, then paste
the elements together and check where we have 579
n <- 3
library(data.table)
setDT(df1)[, which(do.call(paste0, shift(class, seq(n)-1, type = "lead"))=="579")]
#[1] 2 8
或者代替粘贴
我们可以使用 Map
与减少
Or instead of paste
we can use Map
with Reduce
setDT(df1)[, which(Reduce(`&`, Map(`==`, shift(class, seq(n)-1,
type = "lead"), c(5, 7, 9))))]
#[1] 2 8
这篇关于在R数据帧中查找列值遵循序列的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!