Commissar Vasili Karlovic Commissar Vasili Karlovic - 1 year ago 120
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 Source

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

    #create simple data frames with columns named 'A' and 'B'
    #make a list 
    #join data frames column by column, this will preserve their names
            ,.combine=cbind)%do% # don`t forget this directive

The result will be:

       A B
    X1 1 4
    X2 2 5
    X3 3 6

To pick column number 6:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download