How to cbind many data frames with a loop?

旧时模样 提交于 2021-02-05 06:50:32

问题


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


回答1:


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]



回答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)


来源:https://stackoverflow.com/questions/40225650/how-to-cbind-many-data-frames-with-a-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!