If you need to change the text of a specific column while analyzing data in R, I will introduce how to do it. First, let’s create a simple dataset
Name=c("JACK","KATE","BOB","DAVID","MIN")
Nation=c("USA","Spain","France","Germany","Korea")
Sex=c("Male","Female","Male","Male","Male")
Table=data.frame (Name, Nation, Sex)
Table
Name Nation Sex
1 JACK USA Male
2 KATE Spain Female
3 BOB France Male
4 DAVID Germany Male
5 MIN Korea Male
First, let’s rename the column names. We will change the ‘Nation’ column name to ‘Country’ and the ‘Sex’ column name to ‘Gender’. If you enter the following code, the column names will be updated accordingly.
colnames(Table)[2]=c("Country")
colnames(Table)[3]=c("Gender")
Table
Name <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">Country</mark> <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">Gender</mark>
1 JACK USA Male
2 KATE Spain Female
3 BOB France Male
4 DAVID Germany Male
5 MIN Korea Male
If the nationality of DAVID is Canada instead of Germany, you can update by entering the following code:
Table$Country[Table$Country=="Germany"]="Canada" Table Name Country Gender 1 JACK USA Male 2 KATE Spain Female 3 BOB France Male 4 DAVID <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">Canada</mark> Male 5 MIN Korea Male
stringr package
Next, I will introduce how to change variable names using the stringr package. Before we proceed, we need to install the package first.
if(!require(stringr)) install.packages("stringr")
library (stringr)
To change variable names using this package, we can use the str_replace_all function. For example, let’s say we want to replace ‘USA’ with ‘United States’ and ‘KATE’ with ‘Catherine’ in our dataset.
Name=c("JACK","KATE","BOB","DAVID","MIN")
Nation=c("USA","Spain","France","Germany","Korea")
Sex=c("Male","Female","Male","Male","Male")
Table=data.frame (Name, Nation, Sex)
Table
Name Nation Sex
1 JACK USA Male
2 KATE Spain Female
3 BOB France Male
4 DAVID Germany Male
5 MIN Korea Male
Table$Nation= str_replace_all (Table$Nation, 'USA', 'United States')
Table$Name= str_replace_all (Table$Name, 'KATE', 'Catherine')
Table
Name Nation Sex
1 JACK <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">United States</mark> Male
2 <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">Catherine</mark> Spain Female
3 BOB France Male
4 DAVID Germany Male
5 MIN Korea Male

We aim to develop open-source code for agronomy ([email protected])
© 2022 – 2025 https://agronomy4future.com – All Rights Reserved.
Last Updated: 04/30/2023
Your donation will help us create high-quality content.
PayPal @agronomy4furure / Venmo @agronomy4furure / Zelle @agronomy4furure