r - Changing column names of a data frame

ID : 5423

viewed : 92

Tags : rdataframerenamer

Top 5 Answer for r - Changing column names of a data frame

vote vote

96

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

86

I use this:

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

76

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

vote vote

70

Try:

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

53

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

Top 3 video Explaining r - Changing column names of a data frame

Related QUESTION?