1

I wish to create a vector holding the position of elements from one vector in another vector. This is similar to the following questions:

Get the index of the values of one vector in another?

Is there an R function for finding the index of an element in a vector?

The match function in base R works in the simplest case, shown here:

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,3,4,5)
desired.output <- c(1,3,5,7,9)
match(b,a)
#[1] 1 3 5 7 9

However, match does not appear to work in more complex cases shown below. I might need a combination of which and match. In every case I am considering so far a value in b does not appear more often in b than in a. I need a base R solution.

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,5)
desired.output <- c(1,3,4,5,7,9)

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,4,5)
desired.output <- c(1,3,4,5,7,8,9)

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,4,5,5)
desired.output <- c(1,3,4,5,7,8,9,10)

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,1,2,2,3,4,4,5,5)
desired.output <- c(1,2,3,4,5,7,8,9,10)

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,1,2,2,3,3,4,4,5,5)
desired.output <- c(1,2,3,4,5,6,7,8,9,10)
Mark Miller
  • 11,789
  • 22
  • 72
  • 126
  • 1) write a function that finds an index of a n-th occurence of a number in a vector 2) for every value in b, apply the function to a, while counting the occurences 3) put the values into the vector by result – Shamis Dec 01 '20 at 07:42

1 Answers1

2

You are looking for pmatch:

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,3,4,5)
pmatch(b,a)
#[1] 1 3 5 7 9

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,5)
pmatch(b,a)
#[1] 1 3 4 5 7 9

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,4,5)
pmatch(b,a)
#[1] 1 3 4 5 7 8 9

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,4,5,5)
pmatch(b,a)
#[1]  1  3  4  5  7  8  9 10

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,1,2,2,3,4,4,5,5)
pmatch(b,a)
#[1]  1  2  3  4  5  7  8  9 10

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,1,2,2,3,3,4,4,5,5)
pmatch(b,a)
# [1]  1  2  3  4  5  6  7  8  9 10
GKi
  • 27,870
  • 2
  • 18
  • 35