[R] outer problem

Thomas Lumley thomas at biostat.washington.edu
Mon Jun 19 19:52:37 CEST 2000


On Mon, 19 Jun 2000, Erich Neuwirth wrote:

> 
> why does teh following code not work?
> 
> a<-rnorm(50)
> dim(a)<-c(10,5)
> 
> mycov<-function(mat,i,j){
>             sum((mat[,i]-mean(mat[,i]))*(mat[,j]-mean(mat[,j])))
>             }
>             
> covmat<-function(X){
>         outer(1:dim(X)[2],1:dim(X)[2],function(v1,v2){mycov(X,v1,v2)})} 
> 
> from what i know
> covmat(a) should give the covariance matrix of a, but it gives a matrix
> with
> constant elements.
> 
> mycov(a,1,2) ans simlar calls are doing the right thing.
> so somehow i am misunderstanding outer here.

You're misunderstanding outer().

outer(x,y,f) does just one call to f with arguments created by stacking x
and y together in the right way, so f has to be vectorised.

In any case, var(X) returns the covariance matrix of X, much more
efficiently.

	-thomas

Thomas Lumley
Assistant Professor, Biostatistics
University of Washington, Seattle

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list