[R] Change data frame column names
Don MacQueen
macq at llnl.gov
Wed Jul 15 17:14:15 CEST 2009
Try
names(df) <- as.vector(unlist(coltitles))
This will fail if you have more than one row in your data frame coltitles.
Which is why Duncan Murdoch's second email has a better solution.
Given the difficulty in getting the titles out of the data frame in
vector form, I would wonder why you're storing them as data in a data
frame in the first place.
Note also that the default behavior when creating a dataframe is for
character data to be converted to factors. You can see this with
> class(coltitles$v1)
[1] "factor"
That's part of what gave you weird results. So I would suggest
looking at the help pages to figure out how to prevent conversion to
factor.
If you want names(df) to return "col number one" etc, then you have
to create a data frame whose column names are those. You created a
dataframe (coltitles) whose names were "v1", "v2", etc.
For example,
> tmp <- data.frame("col number one"=1, "col number
>two"='foobar',check.names=FALSE)
> names(tmp)
[1] "col number one" "col number two"
But simpler and easier to just do as Duncan suggested, and create a
vector of names.
-Don
At 2:35 PM +0000 7/15/09, 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")
>
>##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"
>
>
>
>##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.
--
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062
More information about the R-help
mailing list