[R] Better way to change the name of a column in a dataframe?

Joerg van den Hoff j.van_den_hoff at fz-rossendorf.de
Fri Dec 15 08:58:00 CET 2006


Ben Fairbank wrote:
> Hello R users --
> 
>  
> 
> If I have a dataframe such as the following, named "frame" with the
> columns intended to be named col1 through col6,
> 
>  
> 
>> frame
> 
>      col1 col2 cmlo3 col4 col5 col6
> 
> [1,]    3   10     2    6    5    7
> 
> [2,]    6    8     4   10    7    1
> 
> [3,]    7    5     1    3    1    8
> 
> [4,]   10    6     5    4    9    2
> 
>  
> 
> and I want to correct or otherwise change the name of one of the
> columns, I can do so with 
> 
>  
> 
>> dimnames(frame)[[2]][which(dimnames(frame)[[2]]=="cmlo3")] <- "col3"
> 
>  
> 
> which renames the offending column:
> 
>  
> 
>> frame
> 
>      col1 col2 col3 col4 col5 col6
> 
> [1,]    3   10    2    6    5    7
> 
> [2,]    6    8    4   10    7    1
> 
> [3,]    7    5    1    3    1    8
> 
> [4,]   10    6    5    4    9    2
> 
>  
> 
> This seems cumbersome and not very intuitive.  How can one accomplish
> this more simply?
> 
>  
well I would simply use

names(frame)[3] = 'col3'

(supposing you know the column number of your offending column anyway).



More information about the R-help mailing list