How to Delete Data Frame Variables by Column Name in R (2 Examples)

On this page you’ll learn how to delete data frame variables by their name in the R programming language.

Creation of Example Data

data(iris)                                 # Load iris
head(iris)                                 # Head of 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

Example 1: Delete Columns with %in%-operator

iris_new1 <- iris[ , ! names(iris) %in%    # Using %in%-operator
                     c("Sepal.Length", "Petal.Length")]
head(iris_new1)                            # Return head of new data
#   Sepal.Width Petal.Width Species
# 1         3.5         0.2  setosa
# 2         3.0         0.2  setosa
# 3         3.2         0.2  setosa
# 4         3.1         0.2  setosa
# 5         3.6         0.2  setosa
# 6         3.9         0.4  setosa

Example 2: Delete Columns with subset() Function

iris_new2 <- subset(iris,                  # Using subset function
                    select = - c(Sepal.Length, Petal.Length))
head(iris_new2)                            # Return head of new data
#   Sepal.Width Petal.Width Species
# 1         3.5         0.2  setosa
# 2         3.0         0.2  setosa
# 3         3.2         0.2  setosa
# 4         3.1         0.2  setosa
# 5         3.6         0.2  setosa
# 6         3.9         0.4  setosa

Related Articles & Further Resources

Here, you may find some additional resources on topics such as variables, dplyr, coding errors, and naming data.

Leave a Reply

Your email address will not be published. Required fields are marked *

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