这扩展了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
)。
我正在寻找一种有效的方法来映射b
和b
元素的索引。
具体来说,我希望有一个a
长度的列表,其中每个元素都是一个向量,其中b
中的元素索引映射到该list(1, 2, 3, c(4,5,6), 7)
元素。
对于此示例,输出应为:
{{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