[R] Change data frame column names

Duncan Murdoch murdoch at stats.uwo.ca
Wed Jul 15 16:52:41 CEST 2009


On 7/15/2009 10:35 AM, Tom Liptrot wrote:
> 
> 
> 
> Hi R helpers,
> 
> I have a data frame and I want to change the column names to names I have held in another data frame, but I am having difficulty. All data framnes are large so i can't input manually. Below is what i have tried so far:
> 
> df<-data.frame(a=1:5, b=2:6, d=3:7, e=4:8)
> coltitles<-data.frame(v1="col number one", v2="col number two", v3="col number three", v4="col number four")

It would be simpler to use

coltitles <- c((v1="col number one", v2="col number two", v3="col number 
three", v4="col number four")

(and the v1=, v2=, etc. are redundant).  Then your first attempt would work.

> 
> ##first attempt
> 
> names(df)<-coltitles
> names(df)
> [1] "1" "1" "1" "1"   ###not what i wanted as I want names(df) to return [1] "col number one" "col number two" "col number three" "col number four"

If you are taking titles from one data frame to put on another as in 
your original code, then use

names(df) <- names(coltitles)

Duncan Murdoch

> 
> 
> ##second attempt
> 
> coltitles<-as.vector(coltitles, mode="character")  ##trying to convert to a character vector after looking at help
> is.vector(coltitles)
> [1] TRUE
> names(df)<-coltitles
> names(df)
> [1] "1" "1" "1" "1"   ###again not what I wanted
> 
> How can I convert the column names?
> 
> Thanks in advance,
> 
> Tom
> 
> Beyond Hotmail - see what else you can do with Windows Live. Find out more.
> _________________________________________________________________
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list