Match vectors in sequence

  • A+
Category:Languages

I have 2 vectors.

x=c("a", "b", "c", "d", "a", "b", "c") y=structure(c(1, 2, 3, 4, 5, 6, 7, 8), .Names = c("a", "e", "b",  "c", "d", "a", "b", "c")) 

I would like to match a to a, b to b in sequence accordingly, so that x[2] matches y[3] rather than y[7]; and x[5] matches y[6] rather than y[1], so on and so forth.

lapply(x, function(z) grep(z, names(y), fixed=T)) 

gives:

[[1]] [1] 1 6  [[2]] [1] 3 7  [[3]] [1] 4 8  [[4]] [1] 5  [[5]] [1] 1 6  [[6]] [1] 3 7  [[7]] [1] 4 8 

which matches all instances. How do I get this sequence:

1 3 4 5 6 7 8 

So that elements in x can be mapped to the corresponding values in y accordingly?


You are actually looking for pmatch

pmatch(x,names(y)) [1] 1 3 4 5 6 7 8 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: