[R] Strange Matrix Multiplication Behaviour
Huntsinger, Reid
reid_huntsinger at merck.com
Mon Oct 4 16:58:47 CEST 2004
I think this is as intended. When you do elementwise multiplication of a
vector by a matrix R there are three important points to keep in mind:
1) element-wise multiplication treats things as vectors
2) when you treat a matrix as a vector you get the _columns_ stacked one on
top of another.
3) R recycles elements of the shorter vector
So tr*(ex[1,]) is the same as multiplying _row_ 1 by the elements of tr, but
(tr*ex)[1,] multiplies the first _column_ of ex by the first 2 elements of
tr, then the second column by the second two, then the third column by the
third two, then recycles for columns 4, 5 and 6. Then the [1,] takes the
first row of the result, so you (tr[1] tr[3] tr[5] tr[1] tr[3] tr[5]) times
the first row. Which looks like what you have.
Reid Huntsinger
-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Wayne Jones
Sent: Monday, October 04, 2004 10:11 AM
To: R help list
Subject: [R] Strange Matrix Multiplication Behaviour
Hi there fellow R-users,
Im seeing some strange behaviour when I multiply a vector by a matrix
Here is my script:
> tr
1 2 3 4 5 6
0.2217903 0.1560525 0.1487908 0.1671354 0.1590643 0.1471667
>
> ex1
a b c d e f
1 0.2309579 -3.279045 -0.6694697 -1.1024404 0.2303928 -1.5527404
2 -0.2865357 -2.519789 -0.1138712 -0.3571832 -2.6727913 -0.3296945
> is.vector(tr)
[1] TRUE
> is.data.frame(ex1)
[1] TRUE
> tr* ex1[1,]
a b c d e f
1 0.05122423 -0.5117031 -0.09961092 -0.1842569 0.03664727 -0.2285117
> (tr* ex1)[1,]
a b c d e f
1 0.05122423 -0.4878917 -0.1064887 -0.2445106 0.03428033 -0.2469855
Notice that the output from tr * ex[1,] is different from (tr* ex1)[1,]
Especially element number 4.
I would naturally expect both vectors to be equivalent.
Can anyone shed any light on my predicament??
> version
_
platform i386-pc-mingw32
arch i386
os mingw32
system i386, mingw32
status
major 1
minor 9.1
year 2004
month 06
day 21
language R
Regards
Wayne Jones
KSS Ltd
Seventh Floor St James's Buildings 79 Oxford Street Manchester M1 6SS
England
Company Registration Number 2800886
Tel: +44 (0) 161 228 0040 Fax: +44 (0) 161 236 6305
mailto:kssg at kssg.com http://www.kssg.com
The information in this Internet email is confidential and m...{{dropped}}
______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html
More information about the R-help
mailing list