Rename multiple columns by names

rename multiple columns in r dplyr
dplyr rename all columns with vector
rename multiple columns in r dataframe
tidyverse rename multiple columns
dplyr rename column by index
rename columns in multiple data frames r
tidyverse rename columns
dplyr::rename_at

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


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

Renaming Column Names for Multiple Columns Together, Rename Multiple Columns at Once. Changing the column names is a common and an important task for any data wrangling works. You want to  rename_if: Rename Multiple Columns based on Data Type You can select the columns based on their data types and rename them with rename_if command from dplyr package. Here is an example of selecting the columns whose data types are numeric including integer and double and applying str_replace function to change the name.


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

Rename multiple columns by names, To rename multiple columns by names, you can use the setnames function from the data. table package which also works for a data frame. Rename Multiple pandas Dataframe Column Names. 20 Dec 2017. # Import modules import pandas as pd # Set ipython's max row display pd.set_option('display.max_row', 1000) # Set iPython's max column width to 50 pd.set_option('display.max_columns', 50)


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

dplyr rename(), idata = rename(idata, Country = `Country Name`). To rename multiple columns the variable names are simply separated by commas. The base R and dplyr way​  Rename single column. Now , tbl_times contains four columns DepTime, ArrTime, ActualElapsedTime and AirTime. Let’s try to modify DepTime column name to DepartureTime by using r dplyr rename column. Verify the column names after applying the dplyr rename() function.


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

5.5.1 Renaming columns, Rename Multiple pandas Dataframe Column Names. 20 Dec 2017. Preliminaries​. # Import modules import pandas as pd # Set ipython's max row display  Renaming Column Names for Multiple Columns Together. Kan Nishida. Updated . 12k 0 5. Information. Project Information. PROJECT NAME . June Project1. NOTE NAME


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

Rename Data Frame Columns in R, With dplyr, it's super easy to rename columns within your dataframe. or indeed if you're in an environment where multiple people are working on the same data, meaning Using colnames() we can take a look at the existing column names: / PostgreSQL RENAME COLUMN: Renaming One or More Columns of a Table PostgreSQL RENAME COLUMN: Renaming One or More Columns of a Table Summary : in this tutorial, you will learn how to use the PostgreSQL RENAME COLUMN clause in the ALTER TABLE statement to rename one or more columns of a table.


Rename Multiple pandas Dataframe Column Names, 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  The RENAME statement allows you to change the names of one or more variables, variables in a list, or a combination of variables and variable lists. The new variable names are written to the output data set only. Use the old variable names in programming statements for the current DATA step. RENAME applies to all output data sets.


Renaming columns with dplyr in R - Holly Emblem, This recipe helps you rename multiple column headers in a Pandas DataFrame 'Yuma']) print(); print(df) # Rename Column Names df.columns = ['Leader',  Can be either the axis name (‘index’, ‘columns’) or number (0, 1). The default is ‘index’. copy bool, default True. Also copy underlying data. inplace bool, default False. Whether to return a new DataFrame. If True then value of copy is ignored. level int or level name, default None. In case of a MultiIndex, only rename labels in the specified level.


How to rename multiple columns in R · GitHub, Given a Pandas DataFrame, let's see how to rename column names. Output: Rename multiple column. Method #2: By assigning a list of new column names​. The concept to rename multiple columns in pandas DataFrame is similar to that under example one. You just need to separate the renaming of each column using a comma: df = df.rename(columns = {'Colors':'Shapes','Shapes':'Colors'}) So this is the full Python code to rename the columns: