[R] Passing in arguments into function

Ivan Calandra ivan.calandra at uni-hamburg.de
Mon Jan 24 10:27:22 CET 2011


Hi,

If you have the formula stored in a string, you could also use 
as.formula in your call to lm, like this:
form <- "x ~ y + z"
lm(as.formula(form))

HTH,
Ivan


Le 1/23/2011 21:38, Joshua Wiley a écrit :
> Hi Paul,
>
> You need to pass the formula object, not a string.  If you have a
> function that is passing one of its arguments down to lm(), just pass
> the argument directly, no need to do anything special.  Here are some
> examples using a built in dataset:
>
> ## wrapper function
> foo<- function(fooform, ...) {
>    summary(lm(formula = fooform, ...))
> }
>
> ## seeing it in action
> foo(mpg ~ hp * wt, data = mtcars)
>
> ## save a formula in an object
> myform<- mpg ~ hp * wt
>
> ## pass the object to foo() which passes it down
> foo(myform, data = mtcars)
>
> ## pass the formula object "myform" directly to lm()
> summary(lm(myform, data = mtcars))
>
> Do one of those answer your question or do what you want?
>
> Hope this helps,
>
> Josh
>
> On Sun, Jan 23, 2011 at 8:46 AM, Paul Evans<p.evans48 at yahoo.com>  wrote:
>> Hi,
>>
>> I had a function that looked like:
>>
>> diff<- lm(x ~ y + z)
>>
>> How can I pass the argument to the 'lm' function on the fly? E.g., if I pass it
>> in as a string (e.g. "x ~ y + z"), then the lm function treats it as a string
>> and not a proper argument.
>>
>> many thanks
>>
>>
>>
>>
>>         [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>

-- 
Ivan CALANDRA
PhD Student
University of Hamburg
Biozentrum Grindel und Zoologisches Museum
Abt. Säugetiere
Martin-Luther-King-Platz 3
D-20146 Hamburg, GERMANY
+49(0)40 42838 6231
ivan.calandra at uni-hamburg.de

**********
http://www.for771.uni-bonn.de
http://webapp5.rrz.uni-hamburg.de/mammals/eng/1525_8_1.php



More information about the R-help mailing list