このmatch(x, y)
関数は、vectorx
の要素内のvectorの要素を検索するのに最適y
です。y
しかし、ベクトルのリストが-おそらく異なる長さである場合、同様の仕事をするための効率的で簡単な方法は何ですか?
つまり、結果はと同じ長さのベクトルであり、i番目の要素は、またはのi番目の要素を含むx
最初のメンバーである必要があります。y
x
NA
x(最初)の各要素が出現するyの要素を見つけるには、次のことを試してください。
## First, a reproducible example
set.seed(44)
x <- letters[1:25]
y <- replicate(4, list(sample(letters, 8)))
y
# [[1]]
# [1] "t" "h" "m" "n" "a" "d" "i" "b"
#
# [[2]]
# [1] "c" "l" "z" "a" "s" "d" "i" "u"
#
# [[3]]
# [1] "b" "k" "e" "g" "o" "i" "h" "j"
#
# [[4]]
# [1] "g" "i" "f" "r" "h" "w" "l" "o"
## Find the element of y first containing the letters a-j
breaks <- c(0, cumsum(sapply(y, length))) + 1
findInterval(match(x, unlist(y)), breaks)
# [1] 1 1 2 1 3 4 3 1 1 3 3 2 1 1 3 NA NA 4 2 1 2 NA 4 NA NA