carol white
2014-Jul-23 19:16 UTC
corresponding replicated el of one matrix in another matrix or vector
Hi,
I have a matrix of unique elements (strings) like v1 and a vector which contains
replicated values of the 2nd column of the first matrix.
v1 =
cbind(c("1","2","3"),c("a","b","c"))
v2 = c(rep("a",5), rep("c",10), rep("b",3))
How can I add a column to v2 that contains the values of the first column of the
first matrix v1 where the 2nd column of v1 matches the values of v2? Do I need
to grep by looping over the nrow of v1 which is very time consuming or is there
a better solution?
the results should be the same as
v3=rbind( c(rep("a",5), rep("c",10), rep("b",3)),
c(rep("1",5), rep("3",10), rep("2",3)))
---------------------------------------------------------------
v1
[,1] [,2] [,3]
[1,] "1" "2" "3"
[2,] "a" "b" "c" > v2
[1] "a" "a" "a" "a" "a"
"c" "c" "c" "c" "c"
"c" "c" "c" "c" "c"
"b" "b" "b"> v3
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
[1,] "a" "a" "a" "a" "a"
"c" "c" "c" "c" "c"
"c" "c" "c" "c"
[2,] "1" "1" "1" "1" "1"
"3" "3" "3" "3" "3"
"3" "3" "3" "3"
[,15] [,16] [,17] [,18]
[1,] "c" "b" "b" "b"
[2,] "3" "2" "2" "2"
[[alternative HTML version deleted]]