[R] Covariance-Variance Matrix and For Loops

R. Michael Weylandt michael.weylandt at gmail.com
Fri Sep 30 15:19:16 CEST 2011

Without seeing cvm1_list, I can't guarantee this will work, but consider this:

testList = list(rnorm(500), rnorm(500), rnorm(500), rnorm(500), rnorm(500))
testMat = simplify2array(testList)
covTest = cov(testMat)

Running your code works on my testList, so I can't help there without
a reproducible example.

One classic that might fit what you are looking for is

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S
Language. Wadsworth & Brooks/C

but you might be better served by the updated

Chambers' "Programming with Data: A Guide to the S language" (2004)

Hope this helps,

Michael Weylandt

On Fri, Sep 30, 2011 at 7:00 AM, sf1979 <simonfuller9 at gmail.com> wrote:
> Hello,
> I am very new to R (as my Subject probably indicates).
> I want to do something that should, I think, be very simple. I have five
> vectors in a list and I want to construct a covariance matrix out of them.
> Given a 5X5 matrix cvm1, and the list of vectors, cvm1_list, I thought the
> following would work (sorry cannot find code tags):
> for(i in 1:5){
>  for(j in 1:5){
>   cvm1[i,j] <- cov(cvm1_list[[i]], cvm1_list[[j]]) } }
> (PS. I know this is not the var-cov matrix yet but I though it might be a
> start.)
> But I get the error:
> Error in cov(cvm1_list[[i]],  cvm1_list[[j]]) :
>  supply both 'x' and 'y' or a matrix-like 'x'
> Strangely, when I try:
> for(i in 1:5){
>  for(j in 1:5){
>   cvm1[i,j] <- cov(cvm1_list[[j]], cvm1_list[[i]]) } }
> I get a different error:
> Error: is.numeric(x) || is.logical(x) is not TRUE.
> So I have two questions:
> 1) How should I generate the matrix from the list of vectors
> 2) Why on earth doesn't the above code work? And why does it give different
> error messages in the two cases? Could someone give me a technical
> explanation of why R does not like the code?
> A more general question, I do not know of any books that describe R from the
> point of view of a programming language per se, rather than a statistical
> tool. Does anyone know of such a reference work that would throw some light
> on error messages such as the above?
> Thanks in advance.
> SF
> --
> View this message in context: http://r.789695.n4.nabble.com/Covariance-Variance-Matrix-and-For-Loops-tp3859441p3859441.html
> Sent from the R help mailing list archive at Nabble.com.
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list