I am interested in obtaining the successive outer-products
of each row with itself. The first such outer-product will
be
1 2 3
[1,2,3]'[1,2,3] = 2 4 6
3 6 9
In order to operate on successive rows, naturally, I think of 'apply'.
The help file says "For example, if X is a matrix, 1 indicates rows,
and 2 indicates columns."
> apply(fred,1,sum)
[1] 6 15 24
clearly applies 'sum' to each of the rows in turn.
It seems to me that apply(fred,1,function(x)x) would pick off
each successive row, returning the original matrix. But clearly
I am wrong.
> apply(fred,1,function(x)x)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
returns not the rows of 'fred' but the columns. By contrast,
> apply(fred,2,function(x)x)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
returns not the columns but the rows. This suggests
to me that if I want to form the successive outer-product of
each row with itself, I shoud execute
> apply(fred,2,function(x)x%o%x)
[,1] [,2] [,3]
[1,] 1 4 9
[2,] 4 10 18
[3,] 7 16 27
[4,] 4 10 18
[5,] 16 25 36
[6,] 28 40 54
[7,] 7 16 27
[8,] 28 40 54
[9,] 49 64 81
which clearly does not give me what I expect in the first three
rows, even though
> fred[1,]%o%fred[1,]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 6
[3,] 3 6 9
which is the answer I seek, and the apply function with the
margin set at 2 does pick off the first row of the matrix 'fred'
> apply(fred,2,function(x)x)[1,]
[1] 1 2 3
In desperation, I try switching the margin from 2 to 1, but
that doesn't work either.
> apply(fred,1,function(x)x%o%x)
[,1] [,2] [,3]
[1,] 1 16 49
[2,] 2 20 56
[3,] 3 24 63
[4,] 2 20 56
[5,] 4 25 64
[6,] 6 30 72
[7,] 3 24 63
[8,] 6 30 72
[9,] 9 36 81
I conjecture that I am overlooking something fundamental about
the use of 'apply': can anyone point me in the right direction?
Perhaps page numbers from any of the following texts:
V&R, Krause, Spector
Please reply to me, and I will post a summary to the list.
Many thanks,
Bruce
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news