Skip to content

Instantly share code, notes, and snippets.

@duttashi
Created July 17, 2017 03:56
Show Gist options
  • Save duttashi/f12c2f042ac9db91423f83fb71806c2d to your computer and use it in GitHub Desktop.
Save duttashi/f12c2f042ac9db91423f83fb71806c2d to your computer and use it in GitHub Desktop.
How to rename multiple columns in R
Say I have
x=data.frame(q=1,w=2,e=3, ...and many many columns...)
what is the most elegant way to rename an arbitrary subset of columns, whose position I don't necessarily know, into some other arbitrary names?
e.g. Say I want to rename "q" and "e" into "A" and "B", what is the most elegant code to do this?
Obviously, I can do a loop
oldnames=c("q","e")
newnames=c("A","B")
for(i in 1:2)names(x)[names(x)==oldnames[i]]=newnames[i]
But I wonder if there is a better way? Maybe using some of the packages? (plyr::rename etc.)
Solution
setnames from the data.tablepackage will work on data.frames or data.tables
library(data.table)
d <- data.frame(a=1:2,b=2:3,d=4:5)
setnames(d, old = c('a','d'), new = c('anew','dnew'))
d
# anew b dnew
# 1 1 2 4
# 2 2 3 5
Note that changes are made by reference, so no copying (even for data.frames!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment