[R] Using variable names in data frame

Prof Brian D Ripley ripley at stats.ox.ac.uk
Fri Dec 22 08:35:42 CET 2000


On Fri, 22 Dec 2000, Michael McStephen wrote:

> Hi All,
> 
> I'm trying to use the names from a data frame to display data in the 
> frame:
> 
> > data.n<-names(data) # put names into a vector called data.n
> data.n[1]
> [1] "ID"
> 
> >
> > paste("data$",data.n[1],sep="") # create the name of the column in 
> the dataframe
> [1] "data$ID"
>  
> > as.symbol(paste("data$",data.n[1],sep=""))
> data$ID
> 
> > eval(as.symbol(paste("data$",data.n[1],sep="")))
> Error in eval(expr, envir, enclos) : Object "data$ID" not found
> > 
> 
> I want to be able to list the contents of data$ID by using data.n[1] 
> just as I would by typing data$ID at the > prompt.

data$ID is not a name but an expression.  So you need to parse it before
evaluation, as in

eval(parse(text=paste("data$",data.n[1],sep="")))

However, I strongly suspect that what you really need is to use
data[, data.n[1]] to get the column named by data.n[1].


> 
> Thanks for any help.
> 
> Michael.
> 
> ----------------------------------------------------------
> Michael McStephen          M.McStephen at papyrus.mhri.edu.au
> MHRI                       Ph:  +613 9389 2931
> Locked Bag 11              Fax: +613 9387 5061
> PARKVILLE 3052
> VICTORIA
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> 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
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
> 

-- 
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 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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