[R] Strange Matrix Multiplication Behaviour
Liaw, Andy
andy_liaw at merck.com
Mon Oct 4 16:48:55 CEST 2004
What you need to realize is that R does vectorized computation in `Fortran'
order. Here's a perhaps more illuminating example:
> tr <- rep(1:2, 3)
> tr
[1] 1 2 1 2 1 2
> ex1 <- as.data.frame(matrix(1:12, 2, 6))
> ex1
V1 V2 V3 V4 V5 V6
1 1 3 5 7 9 11
2 2 4 6 8 10 12
> tr * ex1[1,]
V1 V2 V3 V4 V5 V6
1 1 6 5 14 9 22
> (tr * ex1)[1,]
V1 V2 V3 V4 V5 V6
1 1 3 5 7 9 11
When you do (tr * ex1)[1,], R multiplies tr and ex1 element-by-element,
stacking _columns_ of ex1 to match tr, and recyle the elements of tr to
match the length of the `stacked' ex1.
Andy
> From: Wayne Jones
>
> 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