Commissar Vasili Karlovic Commissar Vasili Karlovic - 1 month ago 11
R Question

How to cbind many data frames with a loop?

I have 105 data frames with xts, zoo class and II want to combine their 6th columns into a data frame.

So, I created a data frame that contains all the data frame names to use it with a 'for' function:

mydata <- AAL

for (i in 2:105) {
k <- top100[i,1] # The first column contains all the data frame names
mydata <- cbind(mydata, k)
}


It's obviously wrong, but I have no idea either how to cbind so many data frames with completely different names (my data frame names are NASDAQ Symbols) nor how to pick the 6th column of all.

Thank you in advance

Answer

Try foreach package. May be there is more elegant way to do this task, but this approach will work.

    library(foreach)
    #create simple data frames with columns named 'A' and 'B'
    df1<-t(data.frame(1,2,3))
    df2<-t(data.frame(4,5,6))
    colnames(df1)<-c('A')
    colnames(df2)<-c('B')
    #make a list 
    dfs<-list(df1,df2)
    #join data frames column by column, this will preserve their names
    foreach(x=1:2
            ,.combine=cbind)%do% # don`t forget this directive
    {
      dfs[[x]]
    }

The result will be:

       A B
    X1 1 4
    X2 2 5
    X3 3 6

To pick column number 6:

df[,6]