How to Rename Variables within Columns in R?
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 Country Gender
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 Canada 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.
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 United States Male
2 Catherine Spain Female
3 BOB France Male
4 DAVID Germany Male
5 MIN Korea Male