On Thu, Jun 14, 2012 at 01:11:45PM +0000, G. Dai wrote:> 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
Hi.
If i understand correctly, each row of B is obtained from the
corresponding row of A by adding mutliples of other rows using
the weights as described. Try the following.
a <- rbind(
c(0, 1, 1, 0),
c(1, 0, 1, 1),
c(0, 0, 0, 1))
w <- a %*% t(a)
diag(w) <- 1
w %*% a
[,1] [,2] [,3] [,4]
[1,] 1 1 2 1
[2,] 1 1 2 2
[3,] 1 0 1 2
The entries of w are the weights except of the diagonal, which
is all ones, since each row of A contributes to the same row of B
with weight one. Is this, what you are looking for?
Petr Savicky.