“final_states”是一个“列表”,所以你可以将“状态”转换为list然后做
final_states %in% list(state)
#[1] FALSE FALSE TRUE FALSE FALSE FALSE
或者使用mapply检查“state”中的所有元素是否存在于“final_states”的每个列表元素中(假设向量和列表元素的长度相同)
f1 <- function(x,y) all(x==y)
mapply(f1, final_states, list(state))
#[1] FALSE FALSE TRUE FALSE FALSE FALSE
或者rbind将列表元素转换成一个矩阵,然后检查“状态”和“m1”的“行”是否相同。
m1 <- do.call(rbind, final_states)
!rowSums(m1!=state[col(m1)])
#[1] FALSE FALSE TRUE FALSE FALSE FALSE
或者
m1[,1]==state[1] & m1[,2]==state[2]
#[1] FALSE FALSE TRUE FALSE FALSE FALSE
更新
如果您需要获取单个TRUE/FALSE
any(mapply(f1, final_states, list(state)))
#[1] TRUE
或者
any(final_states %in% list(state))
#[1] TRUE
或者
list(state) %in% final_states
#[1] TRUE
或者使用fastmatch中的“更快”fmatch
library(fastmatch)
fmatch(list(state), final_states) >0
#[1] TRUE
基准测试
@Richard Sciven 的base R 函数与除fmatch 之外的其他解决方案相比非常快
set.seed(295)
final_states <- replicate(1e6, sample(1:20, 20, replace=TRUE),
simplify=FALSE)
state <- final_states[[151]]
richard <- function() {Position(function(x) identical(x, state),
final_states, nomatch = 0) > 0}
Bonded <- function(){any( sapply(final_states, identical, state) )}
akrun2 <- function() {fmatch(list(state), final_states) >0}
akrun1 <- function() {f1 <- function(x,y) all(x==y)
any(mapply(f1, final_states, list(state)))}
library(microbenchmark)
microbenchmark(richard(), Bonded(), akrun1(), akrun2(),
unit='relative', times=20L)
#Unit: relative
# expr min lq mean median uq
# richard() 35.22635 29.47587 17.49164 15.66833 14.58235
# Bonded() 109440.56885 101382.92450 55252.86141 47734.96467 44289.80309
# akrun1() 167001.23864 138812.85016 75664.91378 61417.59871 62667.94867
# akrun2() 1.00000 1.00000 1.00000 1.00000 1.00000
# max neval cld
# 14.62328 20 a
# 46299.43325 20 b
# 63890.68133 20 c
# 1.00000 20 a