仅针对相同列的 rbind 数据帧

rbind data frames only for same columns

我有 24 个数据框需要合并。 20 个数据框有相同的 238 列,而不是 4 个数据框有 256 列。此外,与其他 20 个数据帧相比,具有 256 列的 4 个数据帧具有不同的列顺序。

例如'answer'、'condition'、'msg_time'、'fix'等(20个数据帧)

例如'acc_value'、'nitem'、'fix'、'button_press_0'、'rotation'、'previous_fix'、'accuracy'、'answer'、'file'、'condition'等(4个数据帧)

我只想绑定所有 24 个数据框中相同的列。 任何建议将不胜感激。谢谢。

这不是最优雅的解决方案,但它确实有效。

df <- data.frame()            # empty data.frame
base_names <- names(a)        # base_names will reflect any data.frame that has 238 observations
list_df <- list(a, b, c)      # list of all your data frames

for(item in list_df){         # create loop

  items <- item[, base_names] # only select columns that match the 238 columns
  df <- rbind(df, items)      # append those to the data.frame

}

df                            # all data.frames rbinded

如果想避免循环,也可以使用lapply

library(plyr)
library(dplyr) 

df <- data.frame()
base_names <- names(a)
list_df <- list(a, b, c)  

lapply(list_df,
       function(x){

         x_cols <- x[, base_names]
         df <- rbind(df, x_cols)

       }) %>% plyr::ldply(rbind)