[R] matrix manipulation

cowboy dgecon at gmail.com
Thu Jun 14 20:24:20 CEST 2012


thank you, Petr.
This is exactly what I'm looking for in my post.
An related question can be how to get an arbitrary weight, say if row1
and row 2 have 1 common value 1, then assign a weight 10, if row 1 and
row 2 have 2 common value 1, then assign a weight 12. I'm not so sure
how to expand your method.
Really  need to refresh my linear algebra;-)
regards,
cal at cowbo

On 6/14/12, Petr Savicky <savicky at cs.cas.cz> wrote:
> 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.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list