[R] merge matrix row data

arun smartpink111 at yahoo.com
Wed Jul 31 15:35:15 CEST 2013


HI,

Please use ?dput()
mat1<- as.matrix(read.table(text="
D0989  D9820  D5629  D4327  D2134
GID_1    1        0        0      1      0
GID_2    0        1        1      0      0
GID_4    0        0        1      0      0
GID_5    1        1        0      0      0
GID_7    0        1        0      0      1
",sep="",header=TRUE))
row.names(mat1)<- gsub("[_]"," ",row.names(mat1))
IslandA<-c("GID 1", "GID 5")
IslandB<- c("GID 2", "GID 4", "GID 7")
 res<-  t(sapply(c("IslandA","IslandB"),function(x) {x1<-mat1[match(get(x),row.names(mat1)),];(!!colSums(x1))*1} ))

 res
#        D0989 D9820 D5629 D4327 D2134
#IslandA     1     1     0     1     0
#IslandB     0     1     1     0     1
A.K.




----- Original Message -----
From: Elaine Kuo <elaine.kuo.tw at gmail.com>
To: "r-help at stat.math.ethz.ch" <r-help at stat.math.ethz.ch>
Cc: 
Sent: Wednesday, July 31, 2013 9:03 AM
Subject: [R] merge matrix row data

Dear list,



I have a matrix showing the species presence-absence on a map.

Its rows are map locations, represented by GridCellID, such as GID1 and GID
5.

Its columns are species ID, such as D0989, D9820, and D5629.

The matrix is as followed.



Now I want to merge the GridCellID according to the map location of each
island.

For instance, Island A consist of GID 1 and 5. Island B consist of GID 2,
4, and 7.

In GID 1 and 5, species D0989 are both 1.

Then I want to merge GID 1 and 5 into Island A, with species D0989 as 1.

The original matrix and the resulting matrix are listed below.

Please kindly advise how to code the calculation in R.

Please do not hesitate to ask if anything is unclear.

Thank you in advance.



Elaine



Original matrix

        D0989   D9820  D5629  D4327  D2134

GID 1    1        0        0       1      0

GID 2    0        1        1       0      0

GID 4    0        0        1       0      0

GID 5    1        1        0       0      0

GID 7    0        1        0       0      1



Resulting matrix

                D0989   D9820  D5629  D4327  D2134

Island A   1        1       0       1       0

Island B   0        1       1       0       1

    [[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