问题
I have 24 data frames that I need to combine. 20 data frames have the same 238 columns, instead 4 data frames have 256 columns. Moreover, the 4 data frames with 256 columns have a different order of columns compared to the other 20 data frames.
E.g. 'answer', 'condition', 'msg_time', 'fix', etc. (20 data frames)
E.g. 'acc_value', 'nitem', 'fix', 'button_press_0', 'rotation', 'previous_fix', 'accuracy', 'answer','file', 'condition', etc. (4 data frames)
I would like to rbind only those columns that are the same in all 24 data frames. Any suggestion would be really appreciated. Thank you.
回答1:
It's not the most elegant solution, but it works.
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
If you want to avoid loops, you can also use 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)
来源:https://stackoverflow.com/questions/33123494/rbind-data-frames-only-for-same-columns