0
votes

I'm trying to use the Merge() function in RStudio. Basically I have two tables with 5000+ rows. They both have the same amount of rows. Although there is no corresponding Columns to merge by. However the rows are in order and correspond. E.g. The first row of dataframe1 should merge with first row dataframe2...2nd row dataframe1 should merge with 2nd row dataframe2 and so on...

Here's an example of what they could look like:

Dataframe1(df1):

+-------------------------------------+
|     Name    |   Sales   |  Location |
+-------------------------------------+
|      Rod    |    123    |    USA    |
|     Kelly   |    142    |    CAN    |
|      Sam    |    183    |    USA    |
|     Joyce   |    99     |    NED    |
+-------------------------------------+

Dataframe2(df2):

+---------------------+
|     Sex   |   Age   |
+---------------------+
|      M    |    23   |
|      M    |    33   |
|      M    |    31   |
|      F    |    45   |
+---------------------+

NOTE: this is a downsized example only.

I've tried to use the merge function in RStudio, here's what I've done:

DFMerged <- merge(df1, df2)

This however increases both the rows and columns. It returns 16 rows and 5 columns for this example. What am I missing from this function, I know there is a merge(x,y, by=) argument but I'm unable to use a column to match them.

The output I would like is:

+----------------------------------------------------------+
|     Name    |   Sales   |  Location |    Sex   |   Age   |
+----------------------------------------------------------+
|      Rod    |    123    |    USA    |     M    |    23   |
|     Kelly   |    142    |    CAN    |     M    |    33   |
|      Sam    |    183    |    USA    |     M    |    31   |
|     Joyce   |    99     |    NED    |     F    |    45   |
+-------------------------------------+--------------------+

I've considering making extra columns in each dataframes, says row# and match them by that.

2
dplyr::bind_cols(df1, df2) or just cbind(df1, df2).Phil

2 Answers

1
votes

You could use cbind:

cbind(df1, df2)

If you want to use merge you could use:

merge(df1, df2, by=0)
1
votes

You could use:

cbind(df1,df2)

This will necessarily work with same number of rows in two data frames