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

Sean Davis sdavis2 at mail.nih.gov
Tue Feb 8 20:34:19 CET 2005


On Feb 8, 2005, at 1:47 PM, Ken Termiso wrote:

> Hello,
>
> 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.
>

If you want to change (or name) only the name in column 12, for example,

names(mydataframe)[12] <- 'new column 12 name'

  will do the trick.


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

You can do this by assigning your rearranged dataframe back to itself 
(carefully):

mydataframe <- mydataframe[c(5:10,1:4),]

Will take the columns 5 through 10 and put them before columns 1 
through 4.  I note "carefully" above because if mydataframe contains, 
for example, 12 columns, the command here would drop columns 11 and 12.

Hope this helps.

Sean




More information about the R-help mailing list