[R] corresponding replicated el of one matrix in another matrix or vector
arun
smartpink111 at yahoo.com
Wed Jul 23 21:59:45 CEST 2014
Try:
rbind(v2,unname(setNames(v1[,1],v1[,2])[v2]))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
v2 "a" "a" "a" "a" "a" "c" "c" "c" "c" "c" "c" "c" "c" "c"
"1" "1" "1" "1" "1" "3" "3" "3" "3" "3" "3" "3" "3" "3"
[,15] [,16] [,17] [,18]
v2 "c" "b" "b" "b"
"3" "2" "2" "2"
A.K.
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"
More information about the R-help
mailing list