user1701545
user1701545

Reputation: 6190

Find indices of vector elements in a another vector

This extends a previous question I asked. I have 2 vectors:

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

I created b from a by eliminating elements of a that are contained in other, comma separated, elements in a (e.g., "d" and "e" in a are contained in "d,e" and therefore only "d,e" is represented in b).

I am looking for an efficient way to map between indices of the elements of a and b.

Specifically, I would like to have a list of the length of b where each element is a vector with the indices of the elements in a that map to that b element.

For this example the output should be:

list(1, 2, 3, c(4,5,6), 7)

Upvotes: 1

Views: 86

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193497

Modifying slightly from my answer at your previous question, try:

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

Upvotes: 2

Related Questions