[R] Sums based on values of other matrix

Sarah Goslee sarah.goslee at gmail.com
Fri Sep 27 00:01:03 CEST 2013


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
http://www.functionaldiversity.org



More information about the R-help mailing list