[R] variable name of variable in dataframe

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Jul 25 13:00:19 CEST 2003


There are easier (and more readable) ways: the simplest is perhaps to use

names(toyframe) <- paste("lion", b, sep=".")

after creating the data frame.  Others are to use  something like

arg <- list(a=c(1,2))
names(args) <- paste("lion", b, sep=".")
toyframe <- do.call("data.frame", args)

or to make use of substitute().  (Those really are `programming on the 
langauge' rather than using R as a text processor.)

On Fri, 25 Jul 2003, Hotz, T. wrote:

> Dear Tobias,
> 
> The trick is "Programming on the Language", see e.g. the "R Language Manual". 
> Construct the expression you want, and have it explicitly parsed and evaluated.
> 
> toy <- function(b=.95){
>   toyframe <- eval(parse(text=paste("data.frame(lion", b, " = c(1, 2))", sep="")))
>   return(toyframe)
> z}
> toy()
> toy(0)
> 
> HTH
> 
> Thomas
> 
> 
> ---
> 
> Thomas Hotz
> Research Associate in Medical Statistics
> University of Leicester
> United Kingdom
> 
> Department of Epidemiology and Public Health
> 22-28 Princess Road West
> Leicester
> LE1 6TP
> Tel +44 116 252-5410
> Fax +44 116 252-5423
> 
> Division of Medicine for the Elderly
> Department of Medicine
> The Glenfield Hospital
> Leicester
> LE3 9QP
> Tel +44 116 256-3643
> Fax +44 116 232-2976
> 
> 
> > -----Original Message-----
> > From: Tobias Verbeke [mailto:tobias_verbeke at skynet.be]
> > Sent: 25 July 2003 11:16
> > To: R-help
> > Subject: [R] variable name of variable in dataframe
> > 
> > 
> > Dear list,
> > 
> > If I have this toy function:
> > 
> > toy <- function(b=.95){
> > toyframe <- data.frame(lion.95 = c(1, 2))
> > return(toyframe)
> > }
> > 
> > How can I obtain that for any value b, 
> > the name of the column becomes "lionb", 
> > i.e. lion.95 if b = .95, lion.85 if b = .85 etc.
> > knowing that .95 (.85 etc.) may also be
> > given as 0.95 (0.85 etc.) but that the
> > result should be lion.95 (lion.85 etc.) 
> > 
> > 
> > Thanks in advance,
> > 
> > Tobias
> > 
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> >
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> 

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list