[R] How to rename columns that start with numbers?

Patrick Connolly p_connolly at slingshot.co.nz
Fri Aug 14 08:02:17 CEST 2009


On Thu, 13-Aug-2009 at 04:24PM -0600, Mark Na wrote:

|> Hello,
|> 
|> My dataframe has new columns that start with the number 1 or 2 (resulting
|> from a reshape cast command).
|> 
|> Instead of having these columns automatically renamed by R so start with the
|> letter X, I would like to rename these columns to start with the characters
|> "SURV_" (e.g., SURV_1, SURV_2).
|> 
|> I can't seen to use grep() to identify and rename the columns starting with
|> either 1 or 2.
|> 
|> Any help would be much appreciated, thanks!
|> 
|> (I know I could rename these manually, but the above is a simpler statement
|> of the actual problem, which involves several dozen columns, so that's why
|> I'd prefer not to so it manually)

Without knowing what your data looked liked before it was reshaped,
it's a bit hard to guess what would be a good way to avoid the
problem, but this might be a case where cure might be easier than
prevention.

If your dataframe has names like these:
> names(junk.df)
[1] "Fruit"    "January"  "February" "X1"       "X2"       "X3"       "X4"      

You can replace each incidence of "X" with "SURV_" this way:

> names(junk.df) <-  gsub("X", "SURV_", names(junk.df))
> names(junk.df)
[1] "Fruit"    "January"  "February" "SURV_1"   "SURV_2"   "SURV_3"   "SURV_4"  

If there are other instances where "X" is a desirable part of the
name, it would be a bit trickier, but not much.

HTH


|> 
|> Mark Na
|> 
|> 	[[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.

-- 
~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.   
   ___    Patrick Connolly   
 {~._.~}                   Great minds discuss ideas    
 _( Y )_  	         Average minds discuss events 
(:_~*~_:)                  Small minds discuss people  
 (_)-(_)  	                      ..... Eleanor Roosevelt
	  
~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.




More information about the R-help mailing list