在另一个向量中查找向量元素的索引

时间:2014-07-14 05:59:52

标签: r list vector

这扩展了a previous question I asked。 我有2个向量:

a <- c("a","b","c","d","e","d,e","f")
b <- c("a","b","c","d,e","f")

我通过删除b中包含在a中其他逗号分隔元素中的a元素,从a创建了a(例如,“d”和“e” “b中包含的内容包含在”d,e“中,因此只有”d,e“代表a)。

我正在寻找一种有效的方法来映射bb元素的索引。

具体来说,我希望有一个a长度的列表,其中每个元素都是一个向量,其中b中的元素索引映射到该list(1, 2, 3, c(4,5,6), 7) 元素。

对于此示例,输出应为:

{{1}}

1 个答案:

答案 0 :(得分:2)

my answer at your previous question稍微修改 ,尝试:

a <- c("a","b","c","d","e","d,e","f")
b <- c("a","b","c","d,e","f")
B <- setNames(lapply(b, gsub, pattern = ",", replacement = "|"), seq_along(b))

lapply(B, function(x) which(grepl(x, a)))
# $`1`
# [1] 1
# 
# $`2`
# [1] 2
# 
# $`3`
# [1] 3
# 
# $`4`
# [1] 4 5 6
# 
# $`5`
# [1] 7