[R] Change data frame column names
Duncan Murdoch
murdoch at stats.uwo.ca
Wed Jul 15 16:59:59 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")
>
> ##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"
Not sure if my first reply went out; it had an error in it, because I
misread what you were trying to do.
You want to assign a character vector as names. You can set it up like
that originally using
coltitles <- c("col number one", "col number two", "col number three",
"col number four")
and then your first attempt will work. If you need to get the names out
of a dataframe, then use
names(x) <- coltitles[1,]
to select the first row (or select some other row if you want) of the
dataframe to use as names.
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