将所有逻辑规则与矩阵以相同的顺序匹配 [英] Match all logic rules with a matrix and in the same order
问题描述
例如,我有一个这样的矩阵
For example, I have a matrix like this
dat <- cbind(1:10,11:20,21:30)
colnames(dat) <- paste0("x",1:ncol(dat))
dat
x1 x2 x3
[1,] 1 11 21
[2,] 2 12 22
[3,] 3 13 23
[4,] 4 14 24
[5,] 5 15 25
[6,] 6 16 26
[7,] 7 17 27
[8,] 8 18 28
[9,] 9 19 29
[10,] 10 20 30
我也有一个带有逻辑规则的向量,例如像这样
I also have a vector with logical rules, for example like this
pat <- c("x1>1 & x2>12","x3>25","x1<x3 & x3>28")
pat
[1] "x1>1 & x2>12" "x3>25" "x1<x3 & x3>28"
我需要检查矩阵以执行规则,并且规则应该按照它们在向量中指定的相同顺序工作.为了更好的理解,我会画
I need to check the matrix for the execution of the rules, and the rules should work in the same sequence in which they are specified in the vector. For a better understanding, I will draw
因此,我想得到一个函数,它接受两个参数,一个矩阵 dat
和一个带有规则 pat
的向量,并返回 true/false.
As a result, I would like to get a function that takes two arguments, a matrix dat
and a vector with rules pat
, and returns true / false.
如果有人愿意帮助我,我会很高兴
If anyone has a desire to help me with this, I will be very happy
推荐答案
这里是一个循环遍历模式的函数,将 matrix
转换为 data.frame
,而eval
使用表达式,if
评估后没有 TRUE 值返回 FALSE 否则检查 unlist
min
index 与 sort
ed one
Here is a function that loops over the pattern, convert the matrix
to data.frame
, while eval
uating the expression, if
there are no TRUE values after evaluation return FALSE or else check if the unlist
min
index is the same as the sort
ed one
f1 <- function(pat, dat) {
tmp <- suppressWarnings(lapply(pat, function(x)
min(which( with(as.data.frame(dat),
eval(parse(text = x)))))))
tmp1 <- unlist(tmp)
i1 <- any(sapply(tmp, is.infinite))
if(i1) FALSE else identical(tmp1, sort(tmp1))
}
f1(pat, dat)
#[1] TRUE
对于更新
pat <- c("x1>1 & x2>12","x3>25","x1<x3 & x3>48")
f1(pat, dat)
#[1] FALSE
这篇关于将所有逻辑规则与矩阵以相同的顺序匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!