[R] Renaming columns in data.frame, inserting/removing columns from data.frame

Mike Prager Mike.Prager at noaa.gov
Tue Feb 8 21:43:25 CET 2005


At 2/8/2005 01:47 PM, Ken Termiso wrote:
>I'm hoping that there is an easier way to rename columns in a data frame 
>other than by using the names() assignment, which requires you to type in 
>all the column names at once for a data.frame, in the case that I simply 
>want to rename a single column in a data frame.

This is ugly but it works, and it avoids the use column indices (which I 
find error-prone):

 > aa = data.frame(a=1:6, b=5:10)       # a simple example
 > aa
   a  b
1 1  5
2 2  6
3 3  7
4 4  8
5 5  9
6 6 10

 > names(aa)[names(aa)=="a"] = "c"       # rename "a" to "c"
 > aa
   c  b
1 1  5
2 2  6
3 3  7
4 4  8
5 5  9
6 6 10

>Also, is there an easy way to move columns in a data frame around relative 
>to the other columns?

Ditto:

 > aa = data.frame(aa["b"],aa["c"])
 > aa
    b c
1  5 1
2  6 2
3  7 3
4  8 4
5  9 5
6 10 6


MHP


-- 
Michael Prager
NOAA Center for Coastal Fisheries and Habitat Research
Beaufort, North Carolina  28516  USA
http://shrimp.ccfhrb.noaa.gov/~mprager/

NOTE: Opinions expressed are personal, not official. No government
endorsement of any product is made or implied.




More information about the R-help mailing list