[R] Multiply row of a matrix

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Tue Feb 21 18:34:30 CET 2017


Why this works does not become clear until you actually pay attention to how matrices are laid out in memory as a vector, and how vector replication works.  Those ideas are not that difficult to learn, but they feel different than in other languages (e.g. matlab) and they make a huge difference when you want to speed things up. Read the appropriate section in the Introduction to R document that comes with R until you see what is happening, and ask for clarification if you are still lost. 
-- 
Sent from my phone. Please excuse my brevity.

On February 21, 2017 9:00:59 AM PST, William Dunlap via R-help <r-help at r-project.org> wrote:
>> Mat * c(3, 1, 0.5)
>     [,1] [,2] [,3]
>[1,]  3.0    6  9.0
>[2,]  4.0    5  6.0
>[3,]  3.5    4  4.5
>
>
>Bill Dunlap
>TIBCO Software
>wdunlap tibco.com
>
>
>On Tue, Feb 21, 2017 at 8:23 AM,  <ac.dasilva at ulg.ac.be> wrote:
>> If we have the following matrix:
>>
>> Mat<-matrix(1:9, byrow=TRUE, nrow=3)
>> Mat
>>
>>      [,1] [,2] [,3]
>> [1,]    1    2    3
>> [2,]    4    5    6
>> [3,]    7    8    9
>>
>>  I would like to have each row multiplied by a different number.
>> So I would like row 1 multiplied by 3, row2 by 1 and row3 by 0.5
>> Which would give:
>>
>>      [,1] [,2] [,3]
>> [1,]    3    6    9
>> [2,]    4    5    6
>> [3,]    3.5  4    4.5
>>
>>
>> Whatever I try, I always obtain
>>      [,1] [,2] [,3]
>> [1,]    3    2  1.5
>> [2,]   12    5  3.0
>> [3,]   21    8  4.5
>>
>> Which corresponds to the columns multiplied by the factors
>>
>> Could anyone help we to get the proper result ?
>> Best, Anne-Christine da Silva
>>
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> 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.
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>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