Changing column names of a data frame Changing column names of a data frame r r

Changing column names of a data frame


Use the colnames() function:

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

You can also subset:

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


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”)  # errornames(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).