[R] Column names of a data frame

Arne Henningsen ahenningsen at email.uni-kiel.de
Thu Aug 26 12:03:03 CEST 2004


On Thursday 26 August 2004 11:31, michael watson (IAH-C) wrote:
> I'm coming out with all the classic problems today ;-)
>
> Can anyone tell me how to change the column names of an already existing
> data frame?  I've read the docs for ?data.frame and ?as.data.frame but
> can't figure it out.

This is a sample data frame:
> myData <- data.frame( col1 = 1:3, col2 = 2:4, col3 = 3:5 )
> myData
  col1 col2 col3
1    1    2    3
2    2    3    4
3    3    4    5

You can change all names by:
> names( myData )<- c( "newcol1", "newcol2", "newcol3" )
> myData
  newcol1 newcol2 newcol3
1       1       2       3
2       2       3       4
3       3       4       5

Or a single name by:
> names( myData )[ 2 ] <- "newcol2"
> myData
  col1 newcol2 col3
1    1       2    3
2    2       3    4
3    3       4    5

Or if you know the name, but not the column number:
> names( myData )[ which( names( myData ) == "newcol2" ) ] <- "verynewcol2"
> myData
  col1 verynewcol2 col3
1    1           2    3
2    2           3    4
3    3           4    5

All the best,
Arne

> I want to make a new data.frame from some of the columns of an existing
> data.frame, but when I do that, the new data.frame columns have the same
> names as the old data.frame's columns, and I want them to be
> different....
>
> Sorry for the lame question....
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html

-- 
Arne Henningsen
Department of Agricultural Economics
University of Kiel
Olshausenstr. 40
D-24098 Kiel (Germany)
Tel: +49-431-880 4445
Fax: +49-431-880 1397
ahenningsen at agric-econ.uni-kiel.de
http://www.uni-kiel.de/agrarpol/ahenningsen/




More information about the R-help mailing list