How to rbind only the common columns of two data sets

后端 未结 3 808

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

3条回答
  •  萌比男神i
    2021-01-12 03:18

    Use intersect to retrieve the common columns.

    dfr1 <- data.frame(x = 1:5, y = runif(5), z = rnorm(5))
    dfr2 <- data.frame(w = letter[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.

提交回复
热议问题