[R] matrix manipulation

G. Dai dgecon at gmail.com
Thu Jun 14 15:11:45 CEST 2012


Dear Rlisters,
I'm writing to ask how to manipulate a matrix or dataframe in a specific way.

To elaborate, let's consider an example. Assume we have the following
3 by 4 matrix A with elements either 0 or 1,
0  1  1  0
1  0  1  1
0  0  0  1

>From the original matrix A, I'd like to generate a new matrix B satisfing
1) B is initially set to be equal to A, and then
2) Each row of B is a weighted sum of rows of A
3) The weight is given by the number of common 1 shared by the rows.
For row 1:
        it has one common 1 with row 2, thus the weight is 1;
        it has zero common 1 with row 3, thus the weight is 0;
For row 2:
        it has one common 1 with row 1, thus the weight is 1;
        it has one common 1 with row 3, thus the weight is 1;
For row 3:
        it has zero common 1 with row 1, thus the weight is 0;
        it has one common 1 with row 2, thus the weight is 1;
4) In this way, the new matrix B is
1  1  2  1
1  1  2  2
1  0  1  2

To do this, I can use loops for each row. But I'm not sure how to get
the weight for each row efficiently.
Second, I'd like to have a method to achieve the goal without loops
since loops is slow when data becomes big.
Any idea?
thanks,
Cal



More information about the R-help mailing list