如果你想找到匹配给定的载体,你可以使用%Iin%
来测试你的更大的载体中“模式”的存在是一个向量的独特元素。运算符%in%
返回一个逻辑向量。将该输出传递到which()
将返回每个TRUE
值的索引,该值可用于对较大向量进行子集归约,以返回与“模式”匹配的所有元素,而不管顺序如何。将子集向量传递给unique()
消除了重复,以便从匹配元素和“模式”向量长度的较大向量中只有一个元素出现。
例如:
> num.data <- c(1, 10, 1, 6, 3, 4, 5, 1, 2, 3, 4, 5, 9, 10, 1, 2, 3, 4, 5, 6)
> num.pattern.1 <- c(1,6,3,4,5)
> num.pattern.2 <- c(1,2,3,4,5)
> num.pattern.3 <- c(1,2,3,4,6)
> unique(num.data[which(num.data %in% num.pattern.1)])
[1] 1 6 3 4 5
> unique(num.data[which(num.data %in% num.pattern.2)])
[1] 1 3 4 5 2
> unique(num.data[which(num.data %in% num.pattern.3)])
[1] 1 6 3 4 2
注意,第一结果巧合的num.pattern.1
顺序相匹配。其他两个向量不匹配模式向量的顺序。
内找到num.data
,您可以使用类似于下面的函数什么模式相匹配的确切顺序:
set.seed(12102015)
test.data <- sample(c(1:99), size = 500, replace = TRUE)
test.pattern.1 <- test.data[90:94]
find_vector <- function(test.data, test.pattern.1) {
# List of all the vectors from test.data with length = length(test.pattern.1), currently empty
lst <- vector(mode = "list")
# List of vectors that meet condition 1, currently empty
lst2 <- vector(mode = "list")
# List of vectors that meet condition 2, currently empty
lst3 <- vector(mode = "list")
# A modifier to the iteration variable used to build 'lst'
a <- length(test.pattern.1) - 1
# The loop to iterate through 'test.data' testing for conditions and building lists to return a match
for(i in 1:length(test.data)) {
# The list is build incrementally as 'i' increases
lst[[i]] <- test.data[c(i:(i+a))]
# Conditon 1
if(sum(lst[[i]] %in% test.pattern.1) == length(test.pattern.1)) {lst2[[i]] <- lst[[i]]}
# Condition 2
if(identical(lst[[i]], test.pattern.1)) {lst3[[i]] <- lst[[i]]}
}
# Remove nulls from 'lst2' and 'lst3'
lst2 <- lst2[!sapply(lst2, is.null)]
lst3 <- lst3[!sapply(lst3, is.null)]
# Return the intersection of 'lst2' and 'lst3' which should be a match to the pattern vector.
return(intersect(lst2, lst3))
}
对于重复性我用set.seed()
,然后创建一个测试数据集和模式。函数find_vector()
有两个参数:第一个是test.data
,它是要检查模式向量的较大数值向量;第二个是test.pattern.1
,它是您希望在test.data
中找到的较短数值向量。首先,创建三个列表:lst
保持test.data
分成等于所述模式矢量的长度,lst2
从lst
满足第一条件,并且lst3
保持模式矢量从lst
认为满足矢量长度的更小的载体第二个条件。第一个条件测试lst
中的向量的元素是否在模式向量中。第二个条件测试来自lst
的向量按顺序和元素匹配模式向量。
这种方法的一个问题是当条件不满足时NULL
值被引入到每个列表中,但是当条件满足时该过程停止。作为参考,您可以打印列表以查看所有测试的向量,满足第一个条件的向量以及满足第二个条件的向量。空值可以被删除。删除空值后,找到lst2
和lst3
的交集将在test.data
中显示相同匹配的模式。
要使用该功能,请确保明确定义了test.data <- 'a numeric vector'
和test.pattern.1 <- 'a numeric vector'
。不需要特殊的软件包。我没有做任何基准测试,但该功能似乎工作得很快。我也没有寻找功能会失败的场景。
你如何得到这些产出目前尚不清楚。请解释你正在做什么从输入到输出。 –
@RichardScriven - 这是非常不清楚的,但它似乎是匹配的集合,即 - 删除第一批最接近的匹配,然后重新开始。 '1:5'与'1,6,3,4,5'非常接近,然后是'1,2,3,4,5',然后是'1,2,3,4,6' – thelatemail
就像一个近似版本这个:http://stackoverflow.com/questions/33027611/how-to-index-a-vector-sequence-within-a-vector-sequence/33028695 – thelatemail