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:


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?

4/11/2019 9:03:22 PM

I use this:

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

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


Did you try just:




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

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.