How to merge data frames in R

0

You will find occasions when you’ll need to merge data from two different data frames. In order to merge two datasets you are required to have at least one variable in common.

Here is an example of how to merge data within R:

> merged.data <- merge(dataset1, dataset2, by="cityID")

Above we merge two data frames based on the id variable cityID.

This is a very basic example of running a merge in R. A merge can happen on multiple variables and can also be used to run variables with different category.

Here is an example of running a merge on two variables:

> merged.data <- merge(dataset1, dataset2, by=c("zipID", "cityID"))

In R you can also merge two files if the unique id variable has a different name in each data set. For example, the id variable may be called cityID in dataset1, but called townID in dataset2:

> merged.data <- merge(dataset1, dataset2, by.x="cityID", by.y="townID")

LEAVE A REPLY