Position of elements from one vector in another vector with R

醉酒当歌 提交于 2021-02-10 18:18:41

问题


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)

回答1:


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


来源:https://stackoverflow.com/questions/65086390/position-of-elements-from-one-vector-in-another-vector-with-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!