R Error: Can’t rename columns that don’t exist – dplyr & plyr (2 Examples)
In this post you’ll learn how to handle the “Error: Can’t rename columns that don’t exist.” in the R programming language.
Preparing the Examples
data(iris) # Example data in R 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 |
data(iris) # Example data in R 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
install.packages("plyr") # Install & load plyr package library("plyr") |
install.packages("plyr") # Install & load plyr package library("plyr")
install.packages("dplyr") # Install & load dplyr library("dplyr") |
install.packages("dplyr") # Install & load dplyr library("dplyr")
Example 1: Replicating the Error Message – Can’t rename columns that don’t exist.
iris_renamed <- rename(iris, # By mistake using rename of dplyr c("Sepal.Length" = "x1", "Sepal.Width" = "x2", "Petal.Length" = "x3", "Petal.Width" = "x4", "Species" = "x5")) # Error: Can't rename columns that don't exist. # x Column `x1` doesn't exist. # Run `rlang::last_error()` to see where the error occurred. |
iris_renamed <- rename(iris, # By mistake using rename of dplyr c("Sepal.Length" = "x1", "Sepal.Width" = "x2", "Petal.Length" = "x3", "Petal.Width" = "x4", "Species" = "x5")) # Error: Can't rename columns that don't exist. # x Column `x1` doesn't exist. # Run `rlang::last_error()` to see where the error occurred.
Example 2: Solving the Error Message – Can’t rename columns that don’t exist.
iris_renamed <- plyr::rename(iris, # Explicitely use rename of plyr c("Sepal.Length" = "x1", "Sepal.Width" = "x2", "Petal.Length" = "x3", "Petal.Width" = "x4", "Species" = "x5")) head(iris_renamed) # Head of updated data # x1 x2 x3 x4 x5 # 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_renamed <- plyr::rename(iris, # Explicitely use rename of plyr c("Sepal.Length" = "x1", "Sepal.Width" = "x2", "Petal.Length" = "x3", "Petal.Width" = "x4", "Species" = "x5")) head(iris_renamed) # Head of updated data # x1 x2 x3 x4 x5 # 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