Home > OS >  R - Concatenate two dataframes in Regards to Column #?
R - Concatenate two dataframes in Regards to Column #?

Time:04-14

Given two dataframes a and b:

> a
X           a           b           c
1 -0.2246894 -1.48167912 -1.65099363
5  0.5559320 -0.87898575 -0.15634590
3  1.8469466 -0.01487524 -0.53098215
2 -0.6875051  0.23880967  0.01824621
11 -0.6735163  0.75485292  0.44154092


> b
X           a          c
6  0.4287284 -0.3295925
8  0.5201492  0.3341251
7 -2.6355570  1.7916780
9 -1.3645337  1.3642276
10 -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
X           a                   b           c
1 -0.2246894              -1.48167912       -1.65099363
2 -0.6875051               0.23880967        0.01824621
3 1.8469466               -0.01487524      -0.53098215
5  0.5559320               -0.87898575     -0.15634590
6  0.4287284                  NA            -0.32959248
7 -2.635557                    NA             1.7916780
8  0.5201492                   NA              0.3341251
9 -1.3645337                   NA              1.3642276
10 -0.4954542                  NA             -0.6660001
11 -0.6735163               0.75485292        0.44154092

I would like to cacatante the two data frames in regards to the order of X, I understand rbind does a similiar feature, but is there a way to keep the order in regards to X, even if some of the values are missing? For example, the new Frame has the order 1,2,3,5?

CodePudding user response:

new <- merge(a, b, all.x=TRUE, all.y=TRUE)

Or after

install.packages("dplyr")
require(dplyr)

new <- full_join(a, b)

CodePudding user response:

The bind_rows() and arrange() functions in the dplyr package should do the trick.

a <- read.table(header=TRUE, text="X         a           b           c
1 -0.2246894 -1.48167912 -1.65099363
5  0.5559320 -0.87898575 -0.15634590
3  1.8469466 -0.01487524 -0.53098215
2 -0.6875051  0.23880967  0.01824621
11 -0.6735163  0.75485292  0.44154092")

b <- read.table(header=TRUE, text="X           a          c
6  0.4287284 -0.3295925
8  0.5201492  0.3341251
7 -2.6355570  1.7916780
9 -1.3645337  1.3642276
10 -0.4954542 -0.6660001")

library(dplyr)
bind_rows(a, b) %>% arrange(X)
  •  Tags:  
  • r
  • Related