Rename multiple columns by names

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!)

Leave a Comment