Dear all, I have a big problem: - I got two matrices, A and B - A shows identifies the value of B, however the values of B must be summed - For instance, 1 1 2 2 2 2 1 1 gives matrix a 3 4 2 1 1 1 2 2 gives matrix b Now the result for the value 1 would be 7 4 which are the rowsums of the values of matrix B given that matrix A has the value 1. How can I do this automatically? I am really puzzled here. Thanks for your help guys, Tobi [[alternative HTML version deleted]]
Hi, You don't say what you want to do with the output, or whether you want to do it with more than one value, but here's one of the many possible ways to get your example: R> A <- matrix(c(1,1,2,2,2,2,1,1), nrow=2, byrow=TRUE) R> B <- matrix(c(3,4,2,1,1,1,2,2), nrow=2, byrow=TRUE) R> A [,1] [,2] [,3] [,4] [1,] 1 1 2 2 [2,] 2 2 1 1 R> B [,1] [,2] [,3] [,4] [1,] 3 4 2 1 [2,] 1 1 2 2 R> ifelse(A == 1, B, 0) [,1] [,2] [,3] [,4] [1,] 3 4 0 0 [2,] 0 0 2 2 R> rowSums(ifelse(A == 1, B, 0)) [1] 7 4 Sarah On Thu, Sep 26, 2013 at 5:51 PM, tobias schlager <tobebryant at me.com> wrote:> Dear all, > > I have a big problem: > - I got two matrices, A and B > - A shows identifies the value of B, however the values of B must be summed > - For instance, > 1 1 2 2 > 2 2 1 1 > gives matrix a > 3 4 2 1 > 1 1 2 2 > gives matrix b > > Now the result for the value 1 would be > 7 > 4 > which are the rowsums of the values of matrix B given that matrix A has the value 1. > > > How can I do this automatically? I am really puzzled here. Thanks for your help guys, > Tobi-- Sarah Goslee functionaldiversity.org
Hi, Try: A<- structure(c(1, 2, 1, 2, 2, 1, 2, 1), .Dim = c(2L, 4L)) B<- structure(c(3, 1, 4, 1, 2, 2, 1, 2), .Dim = c(2L, 4L)) ?B1<- matrix(0,nrow(B),ncol(B)) B1[A==1]<-B[A==1] ?rowSums(B1) #[1] 7 4 A.K. ----- Original Message ----- From: tobias schlager <tobebryant at me.com> To: "r-help at r-project.org" <r-help at r-project.org> Cc: Sent: Thursday, September 26, 2013 5:51 PM Subject: [R] Sums based on values of other matrix Dear all, I have a big problem: - I got two matrices, A and B - A shows identifies the value of B, however the values of B must be summed - For instance, 1 1 2 2 2 2 1 1 gives matrix a 3 4 2 1 1 1 2 2 gives matrix b Now the result for the value 1 would be 7 4 which are the rowsums of the values of matrix B given that matrix A has the value 1. How can I do this automatically? I am really puzzled here. Thanks for your help guys, Tobi ??? [[alternative HTML version deleted]] ______________________________________________ R-help at r-project.org mailing list stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.