On Wed, 29 Sep 2004, Berton Gunter wrote:
John:
Andy and Dimitris have already fully answered your query. However, as you seem to mainly be interested in simple string substitution, I wanted to point out that there is a perhaps more transparent approach using gsub() that does just this.
Here's a slightly more complicated function form to illustrate the idea:
f<-function(a,b){z<-a+b; b+z*sin(b)}
## Get the body of the function and convert it to a character vector: bf<-deparse(body(f))
themorig<-c('a','b') ## original symbols changed<-c('x','y') ## the character strings you wish to substitute for
The problem with this is that it will substitute xx for aa, and xy for ab, and so on. You need at least to tokenize the code, even if you don't necessarily need to parse it.
-thomas
## perform the string substitution for(i in seq(along=changed))bf<-gsub(orig[i],changed[i],bf)
## re-parse the body and change the formals body(f)<-parse(text=bf) names(formals(f))<-changed
ffunction (x, y) { z <- x + y y + z * sin(y) }
substitute's real power lies in its ability to substitute whole expressions bound to a symbol in an environment, and this might be overkill here.
Cheers,
-- Bert Gunter Genentech Non-Clinical Statistics South San Francisco, CA
"The business of the statistician is to catalyze the scientific learning process." - George E. P. Box
-----Original Message----- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED] Sent: Wednesday, September 29, 2004 4:17 AM To: [EMAIL PROTECTED] Subject: [R] defining a template for functions via do.call and substitute.
Hi,
Given a function
fun <- function(a, b) a + b
how do I generate the function 'function(x, y) x + y'?
Working from the help files and Bill Venables' R-news article (June 2002), I have tried various permutations with substitute without success. e.g. do.call("substitute", list(fun, list(a = as.name("x"), b = as.name("y"))))
Regards,
John.
John Gavin <john.gavin at ubs.com>, Quantitative Risk Models and Statistics, UBS Investment Bank, 6th floor, 100 Liverpool St., London EC2M 2RH, UK. Phone +44 (0) 207 567 4289 Fax +44 (0) 207 568 5352
Visit our website at http://www.ubs.com
This message contains confidential information and is intend...{{dropped}}
______________________________________________ [EMAIL PROTECTED] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
______________________________________________ [EMAIL PROTECTED] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Thomas Lumley Assoc. Professor, Biostatistics [EMAIL PROTECTED] University of Washington, Seattle
______________________________________________ [EMAIL PROTECTED] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
