[R] matrix indexing in 'for' loop?

Phil Spector spector at stat.berkeley.edu
Wed Dec 22 02:57:35 CET 2010


To make your loop work, you need to learn about the get function.
I'm not going to give you the details because there are better
approaches available.
First, let's make some data that will give values which can 
be verified.  (All the correlations of the data you created
are exactly equal to 1.)  And to make the code readable, I'll
omit the ts.m prefix.

> set.seed(14)
> dmi = matrix(rnorm(20),4,5)
> soi = matrix(rnorm(20),4,5)
> pe = matrix(rnorm(20),4,5)
> allmats = list(dmi,soi,pe)

Since cor.test won't automatically do the tests for all columns
of a matrix, I'll write a little helper function:

> gettests = function(x)apply(x,2,function(col)cor.test(pe[,2],col)
> tests = lapply(allmats,gettests)

Now tests is a list of length 2, with a list of the output from
cor.test for the five columns of the each matrix with pe[,2]
(Notice that in your program you made no provision to store 
the results anywhere.)

Suppose you want the correlations:

> sapply(tests,function(x)sapply(x,function(test)test$estimate))
            [,1]       [,2]
cor  0.12723615  0.1342751
cor  0.07067819  0.6228158
cor -0.28761533  0.6218661
cor  0.83731828 -0.9602551
cor -0.36050836  0.1170035

The probabilities for the tests can be found similarly:

> sapply(tests,function(x)sapply(x,function(test)test$p.value))
           [,1]       [,2]
[1,] 0.8727638 0.86572490
[2,] 0.9293218 0.37718416
[3,] 0.7123847 0.37813388
[4,] 0.1626817 0.03974489
[5,] 0.6394916 0.88299648

(Take a look at the "Values" section in the help file for cor.test
to get the names of other quantities of interest.)

The main advantage to this approach is that if you add more matrices
to the allmats list, the other steps automaticall take it into account.

Hope this helps.
 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu





On Tue, 21 Dec 2010, govindas at msu.edu wrote:

>
>
> Hi,
>
> I am having trouble with matrices. I?have 2 matrices as given below, and I am interested in using these matrices inside "for" loops used to calculate correlations. I am creating a list with the names of the matrices assuming this list could be indexed inside the 'for' loop to retrieve the matrix values. But, as expected the code throws out an error. Can someone suggest a better way to call these matrices inside the loops?
>
> ts.m.dmi <- matrix(c(1:20), 4, 5)
> ts.m.soi <- matrix(c(21:40), 4, 5)
> ts.m.pe <- matrix(c(21:40), 4, 5)
>
> factors <- c("ts.m.dmi", "ts.m.soi")
> for (j in 0:1){
> y <- factors[j+1]
>
> for (i in 1:5){
>
> cor.pe.y <- cor(ts.m.pe[,2], y[,i])
> ct.tst <- cor.test(ts.m.pe[,2], y[,i])
> }
> }
>
> Thanks for your time.
>
> -- 
> Regards,
> Maha
> Graduate Student
> 	[[alternative HTML version deleted]]
>
>



More information about the R-help mailing list