开发者

Loop two variables one is conditional on another one

I want to make a loop which 开发者_Python百科contains two variables i,j. for each i equals 1:24, j can be 1:24 but I don't know to make this loop;

i=1
while(i<=24)
{
   j=seq(1,24,by=1)

   for (j in j)
   {
      cor[i,j]
   }
}
i=i+1

is this right? my output is cor[i,j].


In order to accomplish your final goal try...

cor(myMatrix)

The result is a matrix containing all of the correlations of all of the columns in myMatrix.

If you want to try to go about it the way you were it's probably best to generate a matrix of all of the possible combinations of your items using combn. Try combn(1:4,2) and see what it looks like for a small example. For your example with 24 columns the best way to cycle through all combinations using a for loop is...

myMatrix <- matrix(rnorm(240), ncol = 24)
myIndex <- combn(1:24,2)
for(i in ncol(myIndex)){
    temp <- cor(myMatrix[,myIndex[1,i]],myMatrix[,myIndex[2,i]])
    print(c(myIndex[,i],temp))
}

So, it's possible to do it with a for loop in R you'd never do it that way.

(and this whole answer is based on a wild guess about what you're actually trying to accomplish because the question, and your comments, are very hard to figure out)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜