R Extract Rows in Data Frame 1 that are not in Data Frame 2 (Example Code)

This article explains how to extract data frame rows that are only in data No. 1 in the R programming language.

Example Data

data(iris)                             # Loading iris data
head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa
iris_small <- iris[- c(3, 8, 22), ]    # Remove some rows from iris data
head(iris_small)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa
# 7          4.6         3.4          1.4         0.3  setosa

Example: Use dplyr Package to Return Rows that are Only Contained in the Larger Data Frame

We have to install and load the dplyr package:

install.packages("dplyr")              # Install dplyr package
library("dplyr")                       # Load dplyr package
setdiff(iris, iris_small)              # setdiff function of dplyr package
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          4.7         3.2          1.3         0.2  setosa
# 2          5.0         3.4          1.5         0.2  setosa
# 3          5.1         3.7          1.5         0.4  setosa

Related Articles & Further Resources

Below, you may find some further resources on topics such as vectors, character strings, ggplot2, and extracting data:

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top