2

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

Uwe
  • 41,420
  • 11
  • 90
  • 134

2 Answers2

3

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]
Alexander Borochkin
  • 4,249
  • 7
  • 38
  • 53
2

First, you should store all of your data.frames in a list. You can then use a combination of lapply and do.call to extract and recombine the sixth columns of each of the data.frames:

# Create sample data
df_list <- lapply(1:105, function(x) {
  as.data.frame(matrix(sample(1:1000, 100), ncol = 10))
})

# Extract the sixth column from each data.frame
extracted_cols <- lapply(df_list, function(x) x[6])

# Combine all of the columns together into a new data.frame
result <- do.call("cbind", extracted_cols)

One way to get all of your preexisting data.frames into a list would be to use lapply along with get:

df_list <- lapply(top100[[1]], get)
Mark Timms
  • 596
  • 3
  • 4