[R] Use function parameter as an unevaluated text string

William Dunlap wdunlap at tibco.com
Thu Jan 30 01:13:24 CET 2014


Use substitute(argumentName) to get the literal argument, as a language object,
and deparse() to convert that into a character vector.  That vector could be quite
long (especially what your function is called via do.call) so you may want to truncate it.

> doit2 <- function (data) 
{
    dataName <- deparse(substitute(data))[1]
    cat("This function is using values from the data frame ",  dataName, "\n")
}
> doit2(mtcars) # a name
This function is using values from the data frame  mtcars 
> doit2(log(mtcars)) # a call
This function is using values from the data frame  log(mtcars)
> do.call2(doit, list(mtcars)) # a value (truncation comes into play here)
This function is using values from the data frame  structure(list(mpg = c(21, 21, 22.8, 21.4, 18.7, 18.1, 14.3,

I like to make dataName an argument to the function, whose default value
is deparse(substitute(data))[1], so you can call your function via another, which
can pass on the name that the user knows the data by or would like to display.

> doit3 <- function(data, dataName=deparse(substitute(data))[1])
{
    cat("This function is using values from the data frame ",  dataName, "\n")
}
> do.call(doit3, list(mtcars, dataName="Motor Cars"))
This function is using values from the data frame  Motor Cars

Bill Dunlap
TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of John Sorkin
> Sent: Wednesday, January 29, 2014 3:48 PM
> To: r-help at r-project.org
> Subject: [R] Use function parameter as an unevaluated text string
> 
> I would like to take a parameter passed to a function as a text string. I don't want the
> parameter evaluated, I want it uses exactly as passed,
> 
> doit <- function(data) {
> 
> cat("This function is using values from the data frame ",data,"\n")
> 
> }
> 
> mydata <- data.frame(x = c(1,2,3), y=c(3,2,1))
> doit(mydata)
> 
> I would like to see the following printed
> 
> This function is using values from the data frame mydata
> 
> Thank you,
> John
> 
> 
> 
> 
> John David Sorkin M.D., Ph.D.
> Professor of Medicine
> Chief, Biostatistics and Informatics
> University of Maryland School of Medicine Division of Gerontology and Geriatric
> Medicine
> Baltimore VA Medical Center
> 10 North Greene Street
> GRECC (BT/18/GR)
> Baltimore, MD 21201-1524
> (Phone) 410-605-7119
> (Fax) 410-605-7913 (Please call phone number above prior to faxing)
> 
> Confidentiality Statement:
> This email message, including any attachments, is for ...{{dropped:9}}




More information about the R-help mailing list