Geiser
Geiser

Reputation: 1089

Replace the contents of a vector with the values of a matrix

Well, I hope I explain it simple:

I have a matrix:

matrix(c("a","b","c",1,2,3), nrow=3, ncol=2)

with output:

     [,1] [,2]
[1,] "a"  "1" 
[2,] "b"  "2" 
[3,] "c"  "3" 

I have a vector, for example:

vector1 <- c("b", "a", "b", "c")

I want that another vector to pick the values associated of the matrix that appear on the vector. I mean, the final vector must be:

[1] 2 1 2 3

I can't figure it out at the moment.

Thank you

Upvotes: 0

Views: 47

Answers (1)

akrun
akrun

Reputation: 887981

Try match where 'm1' is the matrix

 match(vector1, m1[,1])
 #[1] 2 1 2 3

Or

 unname(setNames(as.numeric(m1[,2]), m1[,1])[vector1])
 #[1] 2 1 2 3

Upvotes: 1

Related Questions