[R] Build a matrix from another matrix by specifying the indexes

Petr PIKAL petr.pikal at precheza.cz
Wed Feb 3 10:42:40 CET 2010


Hi

r-help-bounces at r-project.org napsal dne 02.02.2010 21:32:16:

> 
> ke te pehea koe Peter?
> I don't see how I could do this with a merge to be honest...

> mat<-matrix(sample(letters[1:3], 24, replace=T),6,4) 
> mat
     [,1] [,2] [,3] [,4]
[1,] "b"  "c"  "b"  "c" 
[2,] "b"  "a"  "a"  "c" 
[3,] "c"  "b"  "c"  "a" 
[4,] "b"  "b"  "a"  "a" 
[5,] "a"  "a"  "a"  "a" 
[6,] "a"  "c"  "b"  "c" 
> mat2<-matrix(sample(letters[1:5], 24, replace=T),6,4) 
> mat2
     [,1] [,2] [,3] [,4]
[1,] "c"  "a"  "d"  "c" 
[2,] "c"  "b"  "c"  "b" 
[3,] "c"  "c"  "a"  "d" 
[4,] "c"  "b"  "d"  "c" 
[5,] "e"  "c"  "c"  "e" 
[6,] "a"  "b"  "d"  "c" 
> df1<-data.frame(mat)
> df2<-data.frame(mat2)
> merge(df1, df2, all=T)
   X1 X2 X3 X4
1   a  a  a  a
2   a  b  d  c
3   a  c  b  c
4   b  a  a  c
5   b  b  a  a
6   b  c  b  c
7   c  a  d  c
8   c  b  c  a
9   c  b  c  b
10  c  b  d  c
11  c  c  a  d
12  e  c  c  e
> merge(df1, df2, by=c("X1", "X2"), all=T)
   X1 X2 X3.x X4.x X3.y X4.y
1   a  a    a    a <NA> <NA>
2   a  b <NA> <NA>    d    c
3   a  c    b    c <NA> <NA>
4   b  a    a    c <NA> <NA>
5   b  b    a    a <NA> <NA>
6   b  c    b    c <NA> <NA>
7   c  a <NA> <NA>    d    c
8   c  b    c    a    c    b
9   c  b    c    a    d    c
10  c  c <NA> <NA>    a    d
11  e  c <NA> <NA>    c    e

Is this what you want?

Regards
Petr

 


> 
> -----
> Anna Lippel
> -- 
> View this message in context: http://n4.nabble.com/Build-a-matrix-from-
> another-matrix-by-specifying-the-indexes-tp1460326p1460355.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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