例如,我有一个像这样的矩阵
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
我还有一个具有逻辑规则的向量,例如像这样
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
,并返回真/假。
如果有人愿意帮助我,我会很高兴
UPD========================================
我并不总是从函数中得到正确的答案f1
, 可能是什么问题呢?
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))
}
一些虚假数据
set.seed(25641)
dat <- matrix(data = sample(10,20,replace = T),ncol = 3)
colnames(dat) <- paste0("x",1:ncol(dat))
pat <- c("x1>5","x2>x1","x3>1")
> dat
x1 x2 x3
[1,] 4 4 7
[2,] 9 3 4
[3,] 7 9 5
[4,] 3 2 10
[5,] 10 7 10
[6,] 5 6 4
[7,] 9 9 4
According to the data, it can be seen that the function f1
should return TRUE
, but it returns FALSE
f1(pat = pat,dat = dat)
[1] FALSE