Search code examples
rloopslapplydatastore

How to store data from for loop inside of for loop? (rolling correlation in r)


require(quantmod)
require(TTR)

iris2 <- iris[1:4]
b=NULL
for (i in 1:ncol(iris2)){
for (j in 1:ncol(iris2)){
a<- runCor(iris2[,i],iris2[,j],n=21)
b<-cbind(b,a)}}

I want to calculate a rolling correlation of different columns within a dataframe and store the data separately by a column. Although the code above stores the data into variable b, it is not as useful as it is just dumping all the results. What I would like is to be able to create different dataframe for each i.

In this case, as I have 4 columns, what I would ultimately want are 4 dataframes, each containing 4 columns showing rolling correlations, i.e. df1 = corr of col 1 vs col 1,2,3,4, df2 = corr of col 2 vs col 1,2,3,4...etc)

I thought of using lapply or rollapply, but ran into the same problem.

d=NULL
for (i in 1:ncol(iris2))
 for (j in 1:ncol(iris2))
{c<-rollapply(iris2, 21 ,function(x) cor(x[,i],x[,j]), by.column=FALSE)
d<-cbind(d,c)}  

Would really appreciate any inputs.


Solution

  • If you want to keep the expanded loop, how about a list of dataframes?

    e <- list(length = length(ncol(iris2)))
    
    for (i in 1:ncol(iris2)) {
      d <- matrix(0, nrow = length(iris2[,1]), ncol = length(iris2[1,]))
        for (j in 1:ncol(iris2)) {
            d[,j]<- runCor(iris2[,i],iris2[,j],n=21)
        }
    e[[i]] <- d
    }
    

    It's also a good idea to allocate the amount of space you want with placeholders and put items into that space rather than use rbind or cbind.