Combine Two Data Frames by Rows (Rbind) When They Have Different Sets of Columns

Combine two data frames by rows (rbind) when they have different sets of columns

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

Combining data frames with unequal number of columns

There's also rbind.fill from plyr or Stack.

library(plyr)

rbind.fill(Dat1, Dat2)

## Col1 Col2 Col3 Col4 Col5
## 1 A1 56 89 NA <NA>
## 2 A2 49 NA 84 F11

library(Stack)

Stack(Dat1, Dat2)

## Col1 Col2 Col3 Col4 Col5
## 1 A1 56 89 NA <NA>
## 2 A2 49 NA 84 F11

Combine two dataframes by row (irrespective of columns names)

A base R option is list2DF + Map

> list2DF(Map(c, obj1, obj))
emp degree
1 10 1
2 10 1
3 10 1
4 10 1
5 10 1
6 10 1
7 1990 223
8 1991 224
9 1992 225
10 1993 226
11 1994 227
12 1995 228

Also, you can try rbindlist from data.table package

data.table::rbindlist(list(obj1, obj), use.names = FALSE)

which gives

     emp degree
1: 10 1
2: 10 1
3: 10 1
4: 10 1
5: 10 1
6: 10 1
7: 1990 223
8: 1991 224
9: 1992 225
10: 1993 226
11: 1994 227
12: 1995 228

cbind a dataframe with an empty dataframe - cbind.fill?

Here's a cbind fill:

cbind.fill <- function(...){
nm <- list(...)
nm <- lapply(nm, as.matrix)
n <- max(sapply(nm, nrow))
do.call(cbind, lapply(nm, function (x)
rbind(x, matrix(, n-nrow(x), ncol(x)))))
}

Let's try it:

x<-matrix(1:10,5,2)
y<-matrix(1:16, 4,4)
z<-matrix(1:12, 2,6)

cbind.fill(x,y)
cbind.fill(x,y,z)
cbind.fill(mtcars, mtcars[1:10,])

I think I stole this from somewhere.

EDIT STOLE FROM HERE: LINK



Related Topics



Leave a reply



Submit