Combine two data frames by rows (rbind) when they

2018-12-31 04:03发布

Is it possible to row bind two data frames that don't have the same set of columns? I am hoping to retain the columns that do not match after the bind.

13条回答
人气声优
2楼-- · 2018-12-31 04:38

You could also just pull out the common column names.

> cols <- intersect(colnames(df1), colnames(df2))
> rbind(df1[,cols], df2[,cols])
查看更多
无与为乐者.
3楼-- · 2018-12-31 04:40

An alternative with data.table:

library(data.table)
df1 = data.frame(a = c(1:5), b = c(6:10))
df2 = data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
rbindlist(list(df1, df2), fill = TRUE)

rbind will also work in data.table as long as the objects are converted to data.table objects, so

rbind(setDT(df1), setDT(df2), fill=TRUE)

will also work in this situation. This can be preferable when you have a couple of data.tables and don't want to construct a list.

查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 04:43

rbind.fill from the package plyr might be what you are looking for.

查看更多
梦寄多情
5楼-- · 2018-12-31 04:44

You can use smartbind from the gtools package.

Example:

library(gtools)
df1 <- data.frame(a = c(1:5), b = c(6:10))
df2 <- data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
smartbind(df1, df2)
# result
     a  b    c
1.1  1  6 <NA>
1.2  2  7 <NA>
1.3  3  8 <NA>
1.4  4  9 <NA>
1.5  5 10 <NA>
2.1 11 16    A
2.2 12 17    B
2.3 13 18    C
2.4 14 19    D
2.5 15 20    E
查看更多
梦醉为红颜
6楼-- · 2018-12-31 04:46
rbind.ordered=function(x,y){

  diffCol = setdiff(colnames(x),colnames(y))
  if (length(diffCol)>0){
    cols=colnames(y)
    for (i in 1:length(diffCol)) y=cbind(y,NA)
    colnames(y)=c(cols,diffCol)
  }

  diffCol = setdiff(colnames(y),colnames(x))
  if (length(diffCol)>0){
    cols=colnames(x)
    for (i in 1:length(diffCol)) x=cbind(x,NA)
    colnames(x)=c(cols,diffCol)
  }
  return(rbind(x, y[, colnames(x)]))
}
查看更多
情到深处是孤独
7楼-- · 2018-12-31 04:47

If the columns in df1 is a subset of those in df2 (by column names):

df3 <- rbind(df1, df2[, names(df1)])
查看更多
登录 后发表回答