[r] Changing column names of a data frame

I have a data frame called "newprice" (see below) and I want to change the column names in my program in R.

> newprice
   Chang.  Chang.   Chang.
1     100       36      136
2     120      -33       87
3     150       14      164

In fact this is what am doing:

names(newprice)[1]<-paste("premium")
names(newprice)[2]<-paste("change")
names(newprice)[3]<-paste("newprice") 

I have not put this in a loop because I want each column name to be different as you see.

When I paste my program into R console this is the output it gives me:

> names(newprice)[1]<-paste(“premium”)
Error: unexpected input in "names(newprice)[1]<-paste(“"
> names(newprice)[2]<-paste(“change”)
Error: unexpected input in "names(newprice)[2]<-paste(“"
> names(newprice)[3]<-paste(“newpremium”)
Error: unexpected input in "names(newprice)[3]<-paste(“"

I have equally tried using the c() function-for example c("premium"), instead of the paste() function, but to no avail.

Could someone help me to figure this out?

This question is related to r dataframe rename

The answer is


My column names is as below

colnames(t)
[1] "Class"    "Sex"      "Age"      "Survived" "Freq" 

I want to change column name of Class and Sex

colnames(t)=c("STD","Gender","AGE","SURVIVED","FREQ")

The new recommended way to do this is to use the setNames function. See ?setNames. Since this creates a new copy of the data.frame, be sure to assign the result to the original data.frame, if that is your intention.

data_frame <- setNames(data_frame, c("premium","change","newprice"))

Newer versions of R will give you warning if you use colnames in some of the ways suggested by earlier answers.

If this were a data.table instead, you could use the data.table function setnames, which can modify specific column names or a single column name by reference:

setnames(data_table, "old-name", "new-name")

try:

names(newprice) <- c("premium", "change", "newprice")

Use the colnames() function:

R> X <- data.frame(bad=1:3, worse=rnorm(3))
R> X
  bad     worse
1   1 -2.440467
2   2  1.320113
3   3 -0.306639
R> colnames(X) <- c("good", "better")
R> X
  good    better
1    1 -2.440467
2    2  1.320113
3    3 -0.306639

You can also subset:

R> colnames(X)[2] <- "superduper"

Try:

names(newprice)[1] <- "premium"

This may be helpful:

rename.columns=function(df,changelist){
  #renames columns of a dataframe
  for(i in 1:length(names(df))){
    if(length(changelist[[names(df)[i]]])>0){
      names(df)[i]= changelist[[names(df)[i]]]
    }
  }
  df
}

# Specify new dataframe
df=rename.columns(df,list(old.column='new.column.name'))

The error is caused by the "smart-quotes" (or whatever they're called). The lesson here is, "don't write your code in an 'editor' that converts quotes to smart-quotes".

names(newprice)[1]<-paste(“premium”)  # error
names(newprice)[1]<-paste("premium")  # works

Also, you don't need paste("premium") (the call to paste is redundant) and it's a good idea to put spaces around <- to avoid confusion (e.g. x <- -10; if(x<-3) "hi" else "bye"; x).


Use this to change column name by colname function.

colnames(newprice)[1] = "premium"
colnames(newprice)[2] = "change"
colnames(newprice)[3] = "newprice"

I use this:

colnames(dataframe)[which(names(dataframe) == "columnName")] <- "newColumnName"

Similar to the others:

cols <- c("premium","change","newprice")
colnames(dataframe) <- cols

Quite simple and easy to modify.


In case we have 2 dataframes the following works

 DF1<-data.frame('a', 'b')
 DF2<-data.frame('c','d')

We change names of DF1 as follows

 colnames(DF1)<- colnames(DF2)

I had the same issue and this piece of code worked out for me.

names(data)[names(data) == "oldVariableName"] <- "newVariableName"

In short, this code does the following:

names(data) looks into all the names in the dataframe (data)

[names(data) == oldVariableName] extracts the variable name (oldVariableName) you want to get renamed and <- "newVariableName" assigns the new variable name.


If you need to rename not all but multiple column at once when you only know the old column names you can use colnames function and %in% operator. Example:

df = data.frame(bad=1:3, worse=rnorm(3), worst=LETTERS[1:3])

   bad      worse    worst
1   1 -0.77915455       A
2   2  0.06717385       B
3   3 -0.02827242       C

Now you want to change "bad" and "worst" to "good" and "best". You can use

colnames(df)[which(colnames(df) %in% c("bad","worst") )] <- c("good","best")

This results in

  good      worse  best
1    1 -0.6010363    A
2    2  0.7336155    B
3    3  0.9435469    C

There are a couple options with dplyr::rename() and dplyr::select():

library(dplyr)

mtcars %>% 
  tibble::rownames_to_column('car_model') %>%                            # convert rowname to a column. tibble must be installed.
  select(car_model, est_mpg = mpg, horse_power = hp, everything()) %>%   # rename specific columns and reorder
  rename(weight = wt, cylinders = cyl) %>%                               # another option for renaming specific columns that keeps everything by default
  head(2)
      car_model est_mpg horse_power cylinders disp drat weight  qsec vs am gear carb
1     Mazda RX4      21         110         6  160  3.9  2.620 16.46  0  1    4    4
2 Mazda RX4 Wag      21         110         6  160  3.9  2.875 17.02  0  1    4    4

There are also three scoped variants of dplyr::rename(): dplyr::rename_all() for all column names, dplyr::rename_if() for conditionally targeting column names, and dplyr::rename_at() for select named columns. The following example replaces spaces and periods with an underscore and converts everything to lower case:

iris %>%  
  rename_all(~gsub("\\s+|\\.", "_", .)) %>% 
  rename_all(tolower) %>% 
  head(2)
  sepal_length sepal_width petal_length petal_width species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa

dplyr::select_all() can also be used in a similar way:

iris %>%  
  select_all(~gsub("\\s+|\\.", "_", .)) %>% 
  select_all(tolower) %>% 
  head(2)
  sepal_length sepal_width petal_length petal_width species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa

Just to correct and slightly extend Scott Wilson answer.
You can use data.table's setnames function on data.frames too.

Do not expect speed up of the operation but you can expect the setnames to be more efficient for memory consumption as it updates column names by reference. This can be tracked with address function, see below.

library(data.table)
set.seed(123)
n = 1e8

df = data.frame(bad=sample(1:3, n, TRUE), worse=rnorm(n))
address(df)
#[1] "0x208f9f00"
colnames(df) <- c("good", "better")
address(df)
#[1] "0x208fa1d8"
rm(df)

dt = data.table(bad=sample(1:3, n, TRUE), worse=rnorm(n))
address(dt)
#[1] "0x535c830"
setnames(dt, c("good", "better"))
address(dt)
#[1] "0x535c830"
rm(dt)

So if you are hitting your memory limits you may consider to use this one instead.


You can just do the editing by:

newprice <- edit(newprice)

and change the column name manually.


Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to dataframe

Trying to merge 2 dataframes but get ValueError How to show all of columns name on pandas dataframe? Python Pandas - Find difference between two data frames Pandas get the most frequent values of a column Display all dataframe columns in a Jupyter Python Notebook How to convert column with string type to int form in pyspark data frame? Display/Print one column from a DataFrame of Series in Pandas Binning column with python pandas Selection with .loc in python Set value to an entire column of a pandas dataframe

Examples related to rename

Gradle - Move a folder from ABC to XYZ How to rename a component in Angular CLI? How do I completely rename an Xcode project (i.e. inclusive of folders)? How to rename a directory/folder on GitHub website? How do I rename both a Git local and remote branch name? Convert row to column header for Pandas DataFrame, Renaming files using node.js Replacement for "rename" in dplyr Rename multiple columns by names Rename specific column(s) in pandas