[R] Covariance-Variance Matrix and For Loops

sf1979 simonfuller9 at gmail.com
Fri Sep 30 13:00:32 CEST 2011


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.



More information about the R-help mailing list