[R] renaming columns

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Sun Jun 25 11:19:44 CEST 2000


Marc Feldesman <feldesmanm at pdx.edu> writes:

> I frequently get data sets with cryptically-named variables.  The datasets 
> are more useful to me with informative variable names.  I know that I can 
> rename variables using the following command:
> 
> dimname(dataset[[2]][index.of.variable.to.be.renamed]<-new.variable.name
> 
> If I want to do this inside a function (say something I call RenameCol) 
> what is the best way to communicate the new.variable.name back to the 
> calling frame (e.g.)
> 
> RenameCol<-function(dframe, index, newname)
> {
> 	#code to make certain there *are* dimnames
> 	dimname(dframe[[2]][index]<-newname
> 	invisible()
> 	return(dframe)
> }
> 
> The above code works in both SPlus and R if the call looks like:
> 
> dframe<-RenameCol(dframe, 3, "a.new.name")
> 
> Is there a better way to return the new variable name without having to 
> make an explicit assignment at the time of calling RenameCol  (i.e. can the 
> explicit assignment be made more efficiently within the function using 
> "Assign" or "<<-")?
> 
> Be gentle.  Although I've used SPlus and now R for more than a year, I've 
> rarely needed to create functions that change specific attributes of an 
> object.  (I also do not have VR Programming or VR3 at my disposal right now).

Notice that dimnames() on a dataframe is really an add-on construction,
intended to make dataframes matrix-like. However they are really more
list-like and the list of columns have names(). So you can do

names(airquality)[2]<-"Solar.radiation"

If you want to roll that into a function without duplicating the
frame,  you could use slightly dirty tricks like

 RenameCol<-function(dframe, index, newname)
	eval.parent(substitute(names(dframe)[index]<-newname))

but

RenameCol(airquality,2,"Solar.radiation")

is actually 2 characters longer than the names() form...

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list