How to Rename Variables within Columns in R (feat. case_when() code)?

How to Rename Variables within Columns in R (feat. case_when() code)?


In my previous post, I introduced how to change variable names within columns. In the post, I provided a simple code to rename variables and also used the stringr package for renaming variables.


How to Rename Variables within Columns in R?


Today I’ll introduce another code to simply rename variables using dplyr() package.

Name=c("JACK","KATE","BOB","DAVID","MIN")
Country=c("USA","Spain","France","Germany","Korea")
Sex=c("Male","Female","Male","Male","Male")
Table=data.frame (Name, Country, Sex)

print(Table)
   Name Country    Sex
1  JACK     USA   Male
2  KATE   Spain Female
3   BOB  France   Male
4 DAVID Germany   Male
5   MIN   Korea   Male

In my previous post, using the simple data above, I introduced how to rename variables. For example, we can rename variables using the below code.

Table$Country[Table$Country=="Germany"]="Canada" 

print(Table)
   Name Country    Sex
1  JACK     USA   Male
2  KATE   Spain Female
3   BOB  France   Male
4 DAVID  Canada   Male
5   MIN   Korea   Male

Or, using stringr package, we can also rename variables.

if(!require(stringr)) install.packages("stringr")
library (stringr)

Table$Country= str_replace_all (Table$Country, 'USA', 'United States')
Table$Name= str_replace_all (Table$Name, 'KATE', 'Catherine')

print(Table)
       Name       Country    Sex
1      JACK United States   Male
2 Catherine         Spain Female
3       BOB        France   Male
4     DAVID        Canada   Male
5       MIN         Korea   Male


Now, I’ll introduce another code using dplyr() package.

if (require("dplyr") == F) install.packages("dplyr")
library(dplyr)

Table1= Table %>%
              mutate (Country= case_when(
                      Country== "USA"  ~ "california",
                      Country== "Spain"  ~ "Texas",
                      Country== "France"  ~ "Louisiana",
                      Country== "Germany" ~ "New York",
                      Country== "Korea" ~ "Georgia",
                      TRUE ~ as.character(Country)
  ))

print(Table1)
   Name    Country    Sex
1  JACK california   Male
2  KATE      Texas Female
3   BOB  Louisiana   Male
4 DAVID   New York   Male
5   MIN    Georgia   Male

All variables’ name was change. The column name is country is not correct. I’ll change the column name to State.

colnames(Table1)[2] = c("State")

print(Table1)
   Name      State    Sex
1  JACK california   Male
2  KATE      Texas Female
3   BOB  Louisiana   Male
4 DAVID   New York   Male
5   MIN    Georgia   Male

We aim to develop open-source code for agronomy ([email protected])

© 2022 – 2025 https://agronomy4future.com – All Rights Reserved.

Last Updated: 28/02/2025

Your donation will help us create high-quality content.
PayPal @agronomy4furure / Venmo @agronomy4furure / Zelle @agronomy4furure

Comments are closed.