Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 229
Son Avatar asked May 21 '11 11:05

Son


People also ask

How do I change the column name in a DataFrame in R?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.

How do you rename cells in a data frame?

You can use the rename() method of pandas. DataFrame to change column/index name individually. Specify the original name and the new name in dict like {original name: new name} to columns / index parameter of rename() . columns is for the column name, and index is for the index name.


2 Answers

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" 
like image 131
Dirk Eddelbuettel Avatar answered Oct 14 '22 12:10

Dirk Eddelbuettel


I use this:

colnames(dataframe)[which(names(dataframe) == "columnName")] <- "newColumnName" 
like image 23
Matheus Abreu Avatar answered Oct 14 '22 11:10

Matheus Abreu