[R] Column wise matrix multiplication
(Ted Harding)
Ted.Harding at wlandres.net
Mon Feb 20 22:33:28 CET 2012
[See at end]
On 20-Feb-2012 Ted Harding wrote:
> On 20-Feb-2012 Graziano Mirata wrote:
>> Hi all,
>> I am trying to multiply each column of a matrix such to have
>> a unique resulting vector with length equal to the number of
>> rows of the original matrix. In short I would like to do what
>> prod(.) function in Matlab does, i.e.
>>
>> A <-matrix(c(1:10),5,2)
>>
>> V = A[,1]*A[,2]
>>
>> Thank you
>>
>> Graziano
>
> The Matlab prod(A,2) function computes the products along the
> rows of the matrix A and returns the result as a column vector,
> of length equal to the number of rows in A, which seems to be
> what you describe.
>
> Your code above does this for your 2-column example, but the
> result is a simple "R vector" which is not an array (and in
> particular is not a column vector):
>
> A[,1]*A[,2]
> # [1] 6 14 24 36 50
>
> dim(A[,1]*A[,2])
> # NULL
>
> For a matrix A with arbitrary number of columns, if you wanted
> the row sums rather than the row products, you could use the
> R function rowSums():
>
> rowSums(A)
> # [1] 7 9 11 13 15
>
> This is still a dimensionless "simple R vector":
>
> dim(rowSums(A))
> # NULL
>
> Unfortunately, there seems to be no equivalent for products
> (e.g. "rowProds"). But you can define one:
>
> rowProds <- function(X){ apply(X,1,FUN="prod") }
>
> rowProds(A)
> # [1] 6 14 24 36 50
>
> Even then, the result is a "simple R vector", without dimensions:
>
> dim(rowProds(A))
> # NULL
>
> If you need an array (row) vector then you can apply t():
>
> t(rowProds(A))
> # [,1] [,2] [,3] [,4] [,5]
> # [1,] 6 14 24 36 50
>
> or t(t()) for a column vector:
>
> t(t(rowProds(A)))
> # [,1]
> # [1,] 6
> # [2,] 14
> # [3,] 24
> # [4,] 36
> # [5,] 50
>
> Ted.
>
> -------------------------------------------------
Further to the above: I have managed to track down a
function rowProds in the "matrixStats" package:
http://finzi.psych.upenn.edu/R/library/matrixStats/html/rowProds.html
http://www.stats.bris.ac.uk/R/web/packages/matrixStats/matrixStats.pdf
Note that:
"Details
Internally the product is calculated via the logarithmic
transform, treating zeros and negative values specially."
In view of this, which strikes me as potentially getting
close to thin ice, plus the overhead of loading a whole
package just for one function, it may be more straightforward
(and perhaps safer) to define one's own function (as above).
Also (see the PDF reference manual) it is apparently "work
in progress" and also has dependencies on other packages:
see the description at
http://www.stats.bris.ac.uk/R/web/packages/matrixStats/index.html
Ted.
-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 20-Feb-2012 Time: 21:33:25
This message was sent by XFMail
More information about the R-help
mailing list