[英]Match a vector to a list of vectors
I have a list of vectors lis
which I need to match to another vector vec
我有一个矢量列表lis
,我需要匹配另一个矢量vec
lis <- list(c(2,0,0),c(1,1,0), c(1,0,1), c(0,2,0), c(0,1,1), c(0,0,2))
vec <- c(1,1,0)
So either I would get a logical output 所以我要么得到合理的输出
[1] FALSE TRUE FALSE FALSE FALSE FALSE
Or just the position within lis
of the match 或者只是内的位置lis
比赛
I've been trying things along these lines: 我一直在尝试这些方面:
unlist(lis) %in% vec
but the problem is the position of the number is important ie distinguish between c(1,1,0)
and c(1,0,1)
which I haven't been able to do. 但问题是数字的位置很重要,即区分c(1,1,0)
和c(1,0,1)
,这是我无法做到的。 I would like to avoid for
loops as this needs to be quite efficient (fast). 我想避免for
循环,因为这需要非常高效(快速)。
The answers by @agstudy and @Julius involve a loop over the (long) lis
object; @agstudy和@Julius的答案涉及(长) lis
对象的循环; here's an alternative assuming that all elements of lis
are the same length as vec
to allow vector comparison of the unlisted reference 这里是一个替代方案,假设lis
所有元素与vec
长度相同,以允许对未列出的引用进行矢量比较
shortloop <- function(x, lst)
colSums(matrix(unlist(lst) == x, length(x))) == length(x)
which is fast when lis
is long compared to vec
. 与vec
相比, lis
很长时间很快。
longloop <- function(x, lst)
sapply(lst, identical, x)
l1 = rep(lis, 1000)
microbenchmark(shortloop(vec, l1), longloop(vec, l1))
## Unit: microseconds
## expr min lq median uq max neval
## shortloop(vec, l1) 793.009 808.2175 896.299 905.8795 1058.79 100
## longloop(vec, l1) 18732.338 21649.0770 21797.646 22107.7805 24788.86 100
Interestingly, using for
is not that bad from a performance perspective compared to the implicit loop in lapply
(though more complicated and error-prone) 有趣for
是,与lapply
的隐式循环相比,从性能角度来看,使用for
并不是那么糟糕(尽管更复杂且容易出错)
longfor <- function(x, lst) {
res <- logical(length(lst))
for (i in seq_along(lst))
res[[i]] = identical(x, lst[[i]])
res
}
library(compiler)
longforc = cmpfun(longfor)
microbenchmark(longloop(vec, l1), longfor(vec, l1), longforc(vec, l1))
## Unit: milliseconds
## expr min lq median uq max neval
## longloop(vec, l1) 18.92824 21.20457 21.71295 21.80009 23.23286 100
## longfor(vec, l1) 23.64756 26.73481 27.43815 27.61699 28.33454 100
## longforc(vec, l1) 17.40998 18.28686 20.47844 20.75303 21.49532 100
sapply(lis, identical, vec)
# [1] FALSE TRUE FALSE FALSE FALSE FALSE
Benchmark: 基准测试:
l1 <- list(1:1000)[rep(1, 10000)]
v1 <- sample(1000)
AG <- function() sapply(l1,function(x)all(x==v1))
J <- function() sapply(l1, identical, v1)
microbenchmark(AG(), J())
# Unit: milliseconds
# expr min lq median uq max neval
# AG() 76.42732 84.26958 103.99233 111.62671 148.2824 100
# J() 32.14965 37.54198 47.34538 50.93195 104.4036 100
sapply(lis,function(x)all(x==vec))
[1] FALSE TRUE FALSE FALSE FALSE FALSE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.