[R] Using apply to generate matrix from rows?

Stephan Lindner lindners at umich.edu
Mon Jan 19 18:39:31 CET 2009


Dear all,


I have a simple question which I unfortunately do not seem to be able
to solve myself. I have a (NxK) matrix and want to generate a new
matrix by multiplying each row with itself such that the new matrix
has dimension ((N*K)xK) (or better, generate an array with dimension
(K,K,N)). I tried apply, but that did not work. Any suggestions? 

Thanks! 


	Stephan



## Here is a simple example: 

u <- matrix(c(1,2,3,4,5,6,7,8,9,10),nrow=2)

## What I want to obtain 

u[1,]%*%t(u[1,])
u[2,]%*%t(u[2,])

## stacked together --> 10x5 matrix


## This does not work 

sq <- function(x)x%*%t(x)
apply(u,1,function(y)sq(y))






-- 
-----------------------
Stephan Lindner
University of Michigan



More information about the R-help mailing list