78

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

15 Answers 15

102

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

| improve this answer | |
  • 1
    For late arrivals here - Also take a look at Joel's answer below which covers checking for existing columns in case you have a list of name changes which may not all be present e.g. old = c("a", "d", "e") – micstr Nov 7 '16 at 13:29
  • 1
    I wonder, does this work if you only wish to rename a subset / some of the columns instead of all of them? So if I had a data frame of ten columns and wished to rename _id_firstname to firstname and _id_lastname to lastname but leave the remaining eight columns untouched, can I do this or do I have to list all columns? – Mus Jul 9 '18 at 12:43
  • @MusTheDataGuy you supply the subset of new and old names, and it will work. – mnel Jul 16 '18 at 13:20
  • @mnel I need to change the variable names of a subset as @Mus asked. However, the code above did not work for a subset of data. @Gorka's answer with rename_at() worked for changing variable names of a subset. – Mehmet Yildirim Jan 31 at 18:06
87

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
| improve this answer | |
  • 2
    the user asked about passing old and new names as vectors, I think – JelenaČuklina Mar 23 '18 at 12:41
  • 4
    Thanks @Jelena-bioinf. I amended the answer to include your suggestion. – Gorka Mar 24 '18 at 16:08
36

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
| improve this answer | |
23

Here is the most efficient way I have found to rename multiple columns using a combination of purrr::set_names() and a few stringr operations.

library(tidyverse)

# Make a tibble with bad names
data <- tibble(
    `Bad NameS 1` = letters[1:10],
    `bAd NameS 2` = rnorm(10)
)

data 
# A tibble: 10 x 2
   `Bad NameS 1` `bAd NameS 2`
   <chr>                 <dbl>
 1 a                    -0.840
 2 b                    -1.56 
 3 c                    -0.625
 4 d                     0.506
 5 e                    -1.52 
 6 f                    -0.212
 7 g                    -1.50 
 8 h                    -1.53 
 9 i                     0.420
 10 j                     0.957

# Use purrr::set_names() with annonymous function of stringr operations
data %>%
    set_names(~ str_to_lower(.) %>%
                  str_replace_all(" ", "_") %>%
                  str_replace_all("bad", "good"))

# A tibble: 10 x 2
   good_names_1 good_names_2
   <chr>               <dbl>
 1 a                  -0.840
 2 b                  -1.56 
 3 c                  -0.625
 4 d                   0.506
 5 e                  -1.52 
 6 f                  -0.212
 7 g                  -1.50 
 8 h                  -1.53 
 9 i                   0.420
10 j                   0.957
| improve this answer | |
  • 6
    This should be the answer, but could you should also probably expand on what the ~ and . arguments in the set_names() pipe do. – DaveRGP May 24 '18 at 13:41
  • In some cases, you need to explicitly type purrr::set_names(). – Levi Baguley Feb 11 at 20:56
  • 1
    @DaveRGP when using purrr functions, the tilde ~ means "for each column". The . is dplyr syntax for LHS = left hand side of the pipe, i.e the reference to the object which is piped, in this case data. – Agile Bean May 19 at 7:52
11

So I recently ran into this myself, if you're not sure if the columns exist and only want to rename those that do:

existing <- match(oldNames,names(x))
names(x)[na.omit(existing)] <- newNames[which(!is.na(existing))]
| improve this answer | |
6

Building on @user3114046's answer:

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

names(x)[match(oldnames,names(x))] <- newnames

x
#  A w B
#1 1 2 3

This won't be reliant on a specific ordering of columns in the x dataset.

| improve this answer | |
  • 1
    I have upvoted your answer, but I still wonder if there is an even more elegant way to do this, particularly methods that rename by name, instead of by position – qoheleth Jan 8 '14 at 5:34
  • @qoheleth - it is renaming by name! There is no input here that is a positional vector as match takes care of that. The best you're going to do is probably @mnel's setnames answer. – thelatemail Jan 8 '14 at 5:47
  • 1
    it is still sort of renaming by position because, as you said, even though I don't have to explicitly specify a position vector, match is still a position oriented command. In this spirit, I deemed @user3114046's answer position based as well (even thought the %in% command takes care (or tries to) of things). Of course, I suppose you can argue all commands are position oriented when we drill down to the low level mechanism.... but that's not what I mean... the data.table answer is great because there is no multiple calling of the name commands. – qoheleth Jan 8 '14 at 5:56
4

This would change all the occurrences of those letters in all names:

 names(x) <- gsub("q", "A", gsub("e", "B", names(x) ) )
| improve this answer | |
  • 2
    I don't think this is particularly elegant once you get past a couple of rename instances. – thelatemail Jan 8 '14 at 5:13
  • I'm just not good enough to whip up a gsubfn answer. Perhaps G.Grothendieck will come by. He is the regex-meister. – IRTFM Jan 8 '14 at 5:17
4
names(x)[names(x) %in% c("q","e")]<-c("A","B")
| improve this answer | |
  • 2
    Not quite, because as I said, I don't necessarily know the position of the columns, your solution only works if oldnames is sorted so that oldnames[i] occurs before oldnames[j] for i<j. – qoheleth Jan 8 '14 at 5:24
2

You can get the name set, save it as a list, and then do your bulk renaming on the string. A good example of this is when you are doing a long to wide transition on a dataset:

names(labWide)
      Lab1    Lab10    Lab11    Lab12    Lab13    Lab14    Lab15    Lab16
1 35.75366 22.79493 30.32075 34.25637 30.66477 32.04059 24.46663 22.53063

nameVec <- names(labWide)
nameVec <- gsub("Lab","LabLat",nameVec)

names(labWide) <- nameVec
"LabLat1"  "LabLat10" "LabLat11" "LabLat12" "LabLat13" "LabLat14""LabLat15"    "LabLat16" " 
| improve this answer | |
2

Sidenote, if you want to concatenate one string to all of the column names, you can just use this simple code.

colnames(df) <- paste("renamed_",colnames(df),sep="")
| improve this answer | |
2

If the table contains two columns with the same name then the code goes like this,

rename(df,newname=oldname.x,newname=oldname.y)
| improve this answer | |
2

You can use a named vector.

With base R (maybe somewhat clunky):

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

rename_vec <- c(q = "A", e = "B")

names(x) <- ifelse(is.na(rename_vec[names(x)]), names(x), rename_vec[names(x)])

x
#>   A w B
#> 1 1 2 3

Or a dplyr option with !!!:

library(dplyr)

rename_vec <- c(A = "q", B = "e") # the names are just the other way round than in the base R way!

x %>% rename(!!!rename_vec)
#>   A w B
#> 1 1 2 3

The latter works because the 'big-bang' operator !!! is forcing evaluation of a list or a vector.

?`!!`

!!! forces-splice a list of objects. The elements of the list are spliced in place, meaning that they each become one single argument.

| improve this answer | |
  • don't understand how this works - !!!oldnames returns c("A", "B") but which logic transforms this into c("A", "w", "B")?? – Agile Bean May 19 at 7:34
  • @AgileBean I don't know where you found that !!!oldnames would return a vector. It is used to force non-standard evaluation of multiple arguments in dplyr. see ?`!!` Use `!!!` to add multiple arguments to a function. Its argument should evaluate to a list or vector: args <- list(1:3, na.rm = TRUE) ; quo(mean(!!!args)). I think I'll add this explanation to the answer. Cheers for bringing it up – Tjebo May 19 at 9:09
1

Lot's of sort-of-answers, so I just wrote the function so you can copy/paste.

rename <- function(x, old_names, new_names) {
    stopifnot(length(old_names) == length(new_names))
    # pull out the names that are actually in x
    old_nms <- old_names[old_names %in% names(x)]
    new_nms <- new_names[old_names %in% names(x)]

    # call out the column names that don't exist
    not_nms <- setdiff(old_names, old_nms)
    if(length(not_nms) > 0) {
        msg <- paste(paste(not_nms, collapse = ", "), 
            "are not columns in the dataframe, so won't be renamed.")
        warning(msg)
    }

    # rename
    names(x)[names(x) %in% old_nms] <- new_nms
    x
}

 x = data.frame(q = 1, w = 2, e = 3)
 rename(x, c("q", "e"), c("Q", "E"))

   Q w E
 1 1 2 3
| improve this answer | |
  • rename(x, c("q", "e"), c("Q", "E")) no longer seems to work in dplyr rename? – sindri_baldur Mar 8 '18 at 11:09
0

If one row of the data contains the names you want to change all columns to you can do

names(data) <- data[row,]

Given data is your dataframe and row is the row number containing the new values.

Then you can remove the row containing the names with

data <- data[-row,]
| improve this answer | |
0

This is the function that you need: Then just pass the x in a rename(X) and it will rename all values that appear and if it isn't in there it won't error

rename <-function(x){
  oldNames = c("a","b","c")
  newNames = c("d","e","f")
  existing <- match(oldNames,names(x))
  names(x)[na.omit(existing)] <- newNames[which(!is.na(existing))]
  return(x)
}
| improve this answer | |
  • 1
    this seems to be the same as JoelKuiper's answer, but then reframed as function ..... – Jaap Apr 9 '19 at 6:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.