Subject: Re: [R] renaming columns
From: Peter Dalgaard BSA (p.dalgaard@biostat.ku.dk)
Date: Sun 25 Jun 2000 - 19:19:44 EST
Message-ID: <x2ituy86dr.fsf@blueberry.kubism.ku.dk>
Marc Feldesman <feldesmanm@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@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@stat.math.ethz.ch _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
This archive was generated by hypermail 2b25 : Mon 17 Jul 2000 - 12:33:24 EST