Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

r - How to rbind only the common columns of two data sets

I have 2 data frames with different number of columns each. Some of the columns are common between the 2 data frames. How can i rbind only the common columns of the two data frames to a new data frame?

i tried with library(plyr);rbind.fill(A,B) however it sets NA values in the columns that do not match, and this does not help me.

Thanks a lot EC

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use intersect to retrieve the common columns.

dfr1 <- data.frame(x = 1:5, y = runif(5), z = rnorm(5))
dfr2 <- data.frame(w = letters[1:5], x = 6:10, y = runif(5))
common_cols <- intersect(colnames(dfr1), colnames(dfr2))
rbind(
  subset(dfr1, select = common_cols), 
  subset(dfr2, select = common_cols)
)

As pointed out in the comments, you can replace the last line with

rbind(
  dfr1[, common_cols], 
  dfr2[, common_cols]
)

for a small performance and typing improvement.

rbind(
  dfr1[common_cols], 
  dfr2[common_cols]
)

also works but I think that it's a tiny bit less clear.


You can also use dplyr equivalents for the last step.

library(dplyr)
bind_rows(
  dfr1 %>% select({common_cols}), 
  dfr2 %>% select({common_cols})
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...