Combining Data Frames Based On Two Variables in R (Example Code)
In this tutorial you’ll learn how to combine multiple data frames based on more than one ID column in R.
Creation of Exemplifying Data
iris_1 <- iris[1:5, 1:3] # Creating first example data frame iris_1$first_id <- 1:5 iris_1$second_id <- LETTERS[1:5] iris_1 # Returning first example data frame # Sepal.Length Sepal.Width Petal.Length first_id second_id # 1 5.1 3.5 1.4 1 A # 2 4.9 3.0 1.4 2 B # 3 4.7 3.2 1.3 3 C # 4 4.6 3.1 1.5 4 D # 5 5.0 3.6 1.4 5 E |
iris_1 <- iris[1:5, 1:3] # Creating first example data frame iris_1$first_id <- 1:5 iris_1$second_id <- LETTERS[1:5] iris_1 # Returning first example data frame # Sepal.Length Sepal.Width Petal.Length first_id second_id # 1 5.1 3.5 1.4 1 A # 2 4.9 3.0 1.4 2 B # 3 4.7 3.2 1.3 3 C # 4 4.6 3.1 1.5 4 D # 5 5.0 3.6 1.4 5 E
iris_2 <- iris[3:6, 4:5] # Creating first example data frame iris_2$first_id <- 3:6 iris_2$second_id <- LETTERS[3:6] iris_2 # Returning first example data frame # Petal.Width Species first_id second_id # 3 0.2 setosa 3 C # 4 0.2 setosa 4 D # 5 0.2 setosa 5 E # 6 0.4 setosa 6 F |
iris_2 <- iris[3:6, 4:5] # Creating first example data frame iris_2$first_id <- 3:6 iris_2$second_id <- LETTERS[3:6] iris_2 # Returning first example data frame # Petal.Width Species first_id second_id # 3 0.2 setosa 3 C # 4 0.2 setosa 4 D # 5 0.2 setosa 5 E # 6 0.4 setosa 6 F
Example: Applying merge Function Join Data Frames Based On 2 ID Variables
data_merge1 <- merge(iris_1, # Using merge() function in R iris_2, by = c("first_id", "second_id")) data_merge1 # Returning combined data to console # first_id second_id Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 3 C 4.7 3.2 1.3 0.2 setosa # 2 4 D 4.6 3.1 1.5 0.2 setosa # 3 5 E 5.0 3.6 1.4 0.2 setosa |
data_merge1 <- merge(iris_1, # Using merge() function in R iris_2, by = c("first_id", "second_id")) data_merge1 # Returning combined data to console # first_id second_id Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 3 C 4.7 3.2 1.3 0.2 setosa # 2 4 D 4.6 3.1 1.5 0.2 setosa # 3 5 E 5.0 3.6 1.4 0.2 setosa
Related Articles & Further Resources
You may have a look at the following R programming tutorials. They discuss similar topics as this post: