Luma R
2011-May-29 17:45 UTC
[R] constructing nxn matrices involving calculations& conditions based on other tables
Dear R-users, I am having trouble constructing nxn matrices involving calculations& conditions based on other tables. Below I describe a simple example of what I am trying to do: Given the Table A (n x m): Species1 Species2 X A1,1 A1,2 Y A2,1 A2,2 Z A3,1 A3,2 I want to create a matrix M (n xn) X Y Z X - M1,2 M1,3 Y M2,1 - M2,3 Z M3,1 M3,2 - Where M1,2 is equal to the number of common species between X & Y So if: A1,1 = 5; A1,2 =0 A2, 1 = 1; A2,2 =3 Then M1,2 = 1 And also a matrix N (nxn) A B C A - N1,2 N1,3 B N2,1 - N2,3 C N3,1 N3,2 - Where N1,2 is Sum A1,i – Sum A2,i Any help or guidance on where I should look for information on these type of calculations will be very appreciated! Many thanks, Luisa [[alternative HTML version deleted]]
Jabba
2011-May-30 14:20 UTC
[R] constructing nxn matrices involving calculations& conditions based on other tables
Hi Luisa, it was really difficult to manage to understand what you need. Assuming that i've done it correctly this should be similar to what you want: A.matrix <- matrix(rpois(n=28,lambda=2),nrow=7) M.matrix <- matrix(0,nrow=dim(A.matrix)[2],ncol=dim(A.matrix)[2]) for(i in 1:dim(df)[2]) for(j in i:dim(df)[2]) { prod <- df[,i]*df[,j] M.matrix[i,j] <- length(which(prod!=0)) } sums <- apply(A.matrix,2,sum) N.matrix <- matrix(0,nrow=dim(A.matrix)[2],ncol=dim(A.matrix)[2])> for (i in 1:length(sums))for (j in i:length(sums)){ diff <- sums[i]-sums[j] N.matrix[i,j] <- diff } I briefly searched a way to to this without cycling inside objects, but i wasn't able to do it straightforwardly. Probably somebody could give a more efficient and simple hint. Marco.