[R] corresponding replicated el of one matrix in another matrix or vector
Uwe Ligges
ligges at statistik.tu-dortmund.de
Wed Jul 23 22:06:30 CEST 2014
On 23.07.2014 21:16, carol white wrote:
> 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)))
I'd try
t(merge(data.frame(V2=v2), as.data.frame(v1)))
Best,
Uwe Ligges
> ---------------------------------------------------------------
> 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]]
>
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list