Demetri Pananos
Demetri Pananos

Reputation: 7404

Getting the index of an array

Suppose I have a list of names

names = c('Alex','Brad', 'Camilla')

If I had an array like

norder = c(1, 2, 3, 2, 1, 2, 1, 3, 2, 2)

Then I could use norder to access names by doing

names[norder]

>>> c('Alex', 'Brad', 'Camilla', 'Brad', 'Alex', 'Brad', 'Alex',
       'Camilla', 'Brad', 'Brad')

How do I go in the reverse? Given

order= c('Alex', 'Brad', 'Camilla', 'Brad', 'Alex', 'Brad', 'Alex', 'Camilla', 'Brad', 'Brad')

and names, how do I return something that looks like norder?

Upvotes: 2

Views: 35

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73315

match(order, names)
# [1] 1 2 3 2 1 2 1 3 2 2

Upvotes: 3

Related Questions