Rename columns in R
Parag Verma
02 April, 2022
Introduction
package.name<-c("dplyr","stringr")
for(i in package.name){
if(!require(i,character.only = T)){
install.packages(i)
}
library(i,character.only = T)
}
Step 1: Creating dummy data frame
df<-data.frame(ID=1:5,Salary=rnorm(5,200,30))
df
ID Salary
1 1 184.6519
2 2 207.1081
3 3 183.7523
4 4 236.5768
5 5 205.2241
Step 2: Using rename function to change names
Lets change ID to Employee_ID
df2<-df%>%
rename(Employee_ID = ID)
df2
Employee_ID Salary
1 1 184.6519
2 2 207.1081
3 3 183.7523
4 4 236.5768
5 5 205.2241
Lets change Employee_ID to ID and Salary to Net Income
old_nm<-colnames(df2)
new_nm<-c("ID","Net_Income")
df3<-df2%>%
rename_at(vars(old_nm),~new_nm)
Note: Using an external vector in selections is ambiguous.
i Use `all_of(old_nm)` instead of `old_nm` to silence this message.
i See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.
This message is displayed once per session.
df3
ID Net_Income
1 1 184.6519
2 2 207.1081
3 3 183.7523
4 4 236.5768
5 5 205.2241
Parting Comments
In this blog we looked at a very simple example of how single/multiple columns can be easily renamed using dplyr
R Complete Guide
Python Complete Guide
https://www.aimlmadeeasy.com/2021/09/python-complete-guide.html