Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename multiple columns by names

Someone should have asked this already, but I couldn't find an answer. 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.)

like image 996
qoheleth Avatar asked Jan 08 '14 04:01

qoheleth


People also ask

How do I rename only some columns in R?

To rename a column in R you can use the rename() function from dplyr. For example, if you want to rename the column “A” to “B”, again, you can run the following code: rename(dataframe, B = A) .


3 Answers

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

like image 155
mnel Avatar answered Sep 16 '22 11:09

mnel


With dplyr you would do:

library(dplyr)

df = data.frame(q = 1, w = 2, e = 3)
    
df %>% rename(A = q, B = e)

#  A w B
#1 1 2 3

Or if you want to use vectors, as suggested by @Jelena-bioinf:

library(dplyr)

df = data.frame(q = 1, w = 2, e = 3)

oldnames = c("q","e")
newnames = c("A","B")

df %>% rename_at(vars(oldnames), ~ newnames)

#  A w B
#1 1 2 3

L. D. Nicolas May suggested a change given rename_at is being superseded by rename_with:

df %>% 
  rename_with(~ newnames[which(oldnames == .x)], .cols = oldnames)

#  A w B
#1 1 2 3
like image 22
Gorka Avatar answered Sep 18 '22 11:09

Gorka


Another solution for dataframes which are not too large is (building on @thelatemail answer):

x <- data.frame(q=1,w=2,e=3)

> x
  q w e
1 1 2 3

colnames(x) <- c("A","w","B")

> x
  A w B
1 1 2 3

Alternatively, you can also use:

names(x) <- c("C","w","D")

> x
  C w D
1 1 2 3

Furthermore, you can also rename a subset of the columnnames:

names(x)[2:3] <- c("E","F")

> x
  C E F
1 1 2 3
like image 42
Jaap Avatar answered Sep 20 '22 11:09

Jaap