0

I had two dataframes, 1 - Dfa (72 rows) and 2 - Dfb (1495 rows). How do I combine them into a one dataframe. I don't want to do rbind/cbind.

Dfa Dfb
1    1
2    2
3    4
4    5
.    6
.    7
.    8
72   9 
     20
     30
     90
      .
      .
      .
     1495
park
  • 49
  • 6

1 Answers1

2

Not sure if the code below is what you are after

subset(
  merge(
    cbind(id = 1:nrow(dfa), dfa),
    cbind(id = 1:nrow(dfb), dfb),
    all = TRUE
  ),
  select = -id
)

which gives

    a  b
1   1  1
2   2  2
3   3  3
4  NA  4
5  NA  5
6  NA  6
7  NA  7
8  NA  8
9  NA  9
10 NA 10

Dummy Data

dfa <- data.frame(a = 1:3)
dfb <- data.frame(b = 1:10)

If you have multiple data frames more than 2, you can try the following base R code

subset(
  Reduce(
    function(...) merge(..., all = TRUE),
    lapply(list(dfa, dfb, dfc), function(x) cbind(id = 1:nrow(x), x))
  ),
  select = -id
)

which gives

    A  B  C
1   1  1  1
2   2  2  2
3   3  3  3
4  NA  4  4
5  NA  5  5
6  NA  6  6
7  NA  7  7
8  NA  8 NA
9  NA  9 NA
10 NA 10 NA

Dummy Data

dfa <- data.frame(A = 1:3)
dfb <- data.frame(B = 1:10)
dfc <- data.frame(C = 1:7)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81