R - Concatenate two dataframes?

486    Asked by ColemanGarvin in Data Science , Asked on Jun 8, 2021

Given two data frames a and b:

> a
           a           b           c
1 -0.2246894 -1.48167912 -1.65099363
2  0.5559320 -0.87898575 -0.15634590
3  1.8469466 -0.01487524 -0.53098215
4 -0.6875051  0.23880967  0.01824621
5 -0.6735163  0.75485292  0.44154092
> b
           a          c
1  0.4287284 -0.3295925
2  0.5201492  0.3341251
3 -2.6355570  1.7916780
4 -1.3645337  1.3642276
5 -0.4954542 -0.6660001

Is there a simple way to concatenate these so as to return a new data frame of the form below?

> new
           a                   b           c
1  -0.2246894   -1.48167912106676 -1.65099363
2   0.5559320  -0.878985746842256 -0.15634590
3   1.8469466 -0.0148752354840942 -0.53098215
4  -0.6875051   0.238809666690982  0.01824621
5  -0.6735163   0.754852923524198  0.44154092
6   0.4287284                  NA -0.32959248
7   0.5201492                  NA  0.33412510
8  -2.6355570                  NA  1.79167801
9  -1.3645337                  NA  1.36422764
10 -0.4954542                  NA -0.66600006

I want to merge the data frames, match the headers and insert NA in for positions in data frame b where the header is missing.

Answered by Ajit yadav

 To concatenate data frames r, you can use the rbind() function to bind the rows as follows:

Remember column names and the number of columns of the two data frames should be the same.

x <- data.frame(a=c(1,2,3), b=c(4,5,6), c=c(7,8,9))
y <- data.frame(a=c(10,11,12), c=c(13,14,15))
y$b <- NA
new <- rbind(x,y)
 new
   a b c
1 1 4 7
2 2 5 8
3 3 6 9
4 10 NA 13
5 11 NA 14
6 12 NA 15
You can also use the bind_rows() function from the dplyr package as follows:
library("dplyr")
> bind_rows(x,y)
   a b c
1 1 4 7
2 2 5 8
3 3 6 9
4 10 NA 13
5 11 NA 14
6 12 NA 15

Your Answer

Interviews

Parent Categories