Hi Eric,
There are a number of ways you could do this:-
1) Use default values and the missing function: most useful for a set number
of arguments with different actions occurring on each ...
myFun <- function(arg1, arg2=NULL, arg3=NULL, arg4=NULL) {
if (!missing(arg2)) arg1 <- arg1 + arg2 ^ 2
if (!missing(arg3)) arg1 <- arg1 + arg3 ^ 3
if (!missing(arg4)) arg1 <- arg1 + arg4 ^ 4
arg1
}
myFun(4, arg4=2)
2) Use ellipses: most useful for an unknown number of arguments ...
myFun <- function(arg1, ...) {
listOfArgs <- list(...)
listOfArgs <- sapply(listOfArgs, "^", 2)
arg1 + sum(listOfArgs)
}
myFun(4, arg2=4, arg3=4, arg4=2, arg5=3)
Hope this helps,
Rich.
mangosolutions
Tel +44 118 902 6617
Fax +44 118 902 6401
From: s-news-owner@lists.biostat.wustl.edu
[mailto:s-news-owner@lists.biostat.wustl.edu] On Behalf Of Eric yang
Sent: 25 November 2005 12:08
To: s-news@wubios.wustl.edu
Subject: [S] allowing for missing arguments in functions
Dear members,
I've created a function that reads in 10 arguments in the function call,
example
my.fun <- function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9,
arg10) {
...
}
I use all the arguments in the body of the function. Is there a neat way of
allowing for missing arguments in the function call and not executing the
code in the body of the function that refers to the missing arguments?
Any help is much appreciated.
Eric
Yahoo! Personals
Single? There's someone we'd like you to meet.
Lot's of someone's, actually. Yahoo! Personals
<http://us.rd.yahoo.com/evt=36108/*http://personals.yahoo.com >
<<attachment: winmail.dat>>
|