[英]R: match a vector in another vector as a whole
Is there an easy, straightforward way (possibly a builtin function) that could match one vector as a whole in another vector? 是否有一种简单,直接的方法(可能是内置函数)可以在另一个向量中将一个向量作为一个整体匹配? Example: 例:
target <- c(1,2,3)
A <- c(4,5,6,1,2,3)
B <- c(4,5,6,3,2,1)
my_match(target, A) # TRUE
my_match(target, B) # FALSE
I tried %in%
, match
and pmatch
but these won't give the desired result. 我试图%in%
, match
和pmatch
但这些不会得到预期的结果。 For example, both target %in% A
and target %in% B
will give the result [1] TRUE TRUE TRUE
, which is not what I want. 例如, target %in% A
target %in% B
都将给出结果[1] TRUE TRUE TRUE
,这不是我想要的。
Here another version 这是另一个版本
multi_match=function(target,A) {
lA=length(A)
lt=length(target)
if (lt>lA) return(FALSE)
any(colSums(sapply(1:(lA-lt+1),function(i) A[i:(i+lt-1)])==target)==lt)
}
Let's try it with some data 让我们尝试一些数据
target <- c(1,2,3)
A <- c(4,5,6,1,2,3,1,2,3,1,3)
B <- c(4,5,6,3,2,1)
multi_match(target,A)
#TRUE
multi_match(target,B)
#FALSE
#"wrong" input order - trivially no match
multi_match(A,target)
#FALSE
And an extension of the multi_match
function above to multi_which
. 并且上面的multi_match
函数的扩展名为multi_which
。
multi_which=function(target,A) {
lA=length(A)
lt=length(target)
if (lt>lA) return(integer(0))
which(colSums(sapply(1:(lA-lt+1),function(i) A[i:(i+lt-1)])==target)==lt)
}
multi_which(target,A)
#[1] 4 7
multi_which(target,B)
#integer(0)
#"wrong" input order - trivially no match
multi_which(A,target)
#integer(0)
Try: 尝试:
grepl(paste(target,collapse=","),paste(A,collapse=","))
grepl(paste(target,collapse=","),paste(B,collapse=","))
This concatenates the vectors into strings and looks for a substring in the second argument that matches the first. 这将向量连接成字符串,并在第二个参数中查找与第一个匹配的子字符串。
You could put this into a function that returns true or false: 你可以把它放到一个返回true或false的函数中:
my_match <- function(x,y,dlm=",") grepl(paste(x,collapse=dlm),paste(y,collapse=dlm))
my_match(target,A)
[1] TRUE
my_match(target,B)
[1] FALSE
One possible way is to use match
and check if resulting sequence is rising 一种可能的方法是使用match
并检查结果序列是否正在上升
all(diff(match(target, A)) == 1) && length(match(target, A)) == length(target)
Or as a function 或者作为一种功能
> exact_match <- function(p, x) all(diff(match(p, x)) == 1) && length(match(p, x)) == length(p)
> exact_match(target,A)
[1] TRUE
> exact_match(target,B)
[1] FALSE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.