I am sure the answer to this is up somewhere, but I don’t think I’ve been using the right search terms.
Here is my issue. I have multiple matrices (I will simplify to just two here), where each row is a uniquely labeled individual (some of which are shared between matrices, and some of which are not), and common column headings that are shared.
For example:
first<-matrix(rbinom(20,1,.5),4,5)
first[,1]=c(122,145,186,199)
colnames(first)<-c("ID",901,902,903,904)
first
ID 901 902 903 904
[1,] 122 1 0 0 0
[2,] 145 0 0 0 1
[3,] 186 0 0 1 1
[4,] 199 1 0 0 0
second<-matrix(rbinom(30,1,.5),6,5)
second[,1]=c(122,133,142,151,186,199)
colnames(second)<-c("ID",901,902,903,904)
second
ID 901 902 903 904
[1,] 122 0 1 1 1
[2,] 133 0 0 0 1
[3,] 142 1 1 0 1
[4,] 151 0 1 0 0
[5,] 186 1 0 1 1
[6,] 199 1 0 0 0
I would like to add ‘first’ and ‘second’ together based upon the ‘ID’ and column names. This should result in a matrix with 7 rows (since there are 4 IDs in the ‘first’ matrix, and 3 new and 3 old IDs in the ‘second’ matrix: “122,133,142,145,151,186,199”), and the same number of columns.
In this example, the result I would want would be:
ID 901 902 903 904
[1,] 122 1 1 1 1
[2,] 133 0 0 0 1
[3,] 142 1 1 0 1
[4,] 145 0 0 0 1
[5,] 151 0 1 0 0
[6,] 186 1 0 2 2
[7,] 199 2 0 0 0
I was looking for a solution without a “for” loop using builtin functions without success.
So here is my approach