Sheila
Sheila

Reputation: 2596

Combining two data frames into two columns in R

I would like to combine two data frames into two columns in R:

Here is an example of the two data frames:

Data frame XY:

 X     Y
 x1    y1
 x2    y2
 x3    y3
 x4    y4
 x5    y5

Data frame XZ:

 X     Z
 x1    z1
 x2    z2
 x3    z3
 x4    z4
 x5    z5

I want the outcome to be one data frame that looks like this:

 X     YZ
 x1    y1
 x2    y2
 x3    y3
 x4    y4
 x5    y5
 x1    z1
 x2    z2
 x3    z3
 x4    z4
 x5    z5

Here is the code in R for the sample data frames above:

x <- c("x1", "x2", "x3", "x4", "x5")
y <- c("y1", "y2", "y3", "y4", "y5")
z <- c("z1", "z2", "z3", "z4", "z5")

XY <- data.frame(x,y)
XZ <- data.frame(x,z)

I've tried rbind() but haven't had much luck. Merge only merges data frames by adding columns too. I'm not really sure how to go about this.

Upvotes: 1

Views: 420

Answers (3)

Shaz
Shaz

Reputation: 25

If you want Y and Z values for every x value, then you could use full outer merge like this: XYZ <- merge(x = XY, y = YZ, by = "x", all = TRUE)

Otherwise you could simple bind the two data frames by rows as :

XYZ <- rbind(XY, YZ)

Upvotes: 0

eddi
eddi

Reputation: 49448

It's worth mentioning here that the rbind function in data.table has the functionality you want:

library(data.table)

xy = data.table(XY)
xz = data.table(XZ)
rbind(xy, xz, use.names = F)

# or convert them to `data.table` on the fly
.rbind.data.table(XY, XZ, use.names = F)
#     x  y
# 1: x1 y1
# 2: x2 y2
# 3: x3 y3
# 4: x4 y4
# 5: x5 y5
# 6: x1 z1
# 7: x2 z2
# 8: x3 z3
# 9: x4 z4
#10: x5 z5

Upvotes: 3

Jd Baba
Jd Baba

Reputation: 6118

May be you could try renaming the column names as follows:

names(XY)<- c("x","yz")
names(XZ)<- c("x","yz")
new <- rbind(XY,XZ)
> new
    x yz
1  x1 y1
2  x2 y2
3  x3 y3
4  x4 y4
5  x5 y5
6  x1 z1
7  x2 z2
8  x3 z3
9  x4 z4
10 x5 z5

I hope it helps.

I believe in order to use rbind you need to have the same column names.

Upvotes: 5

Related Questions