On Wed, 2010-03-10 at 11:28 +0100, Christophe Genolini
wrote:> Hi the list
>
> I define a S3 function that can have a various number of argument using
> '...'
> When some arguments are missing, I would like to give them some default
> value:
>
> func.numeric <- function(x,...){
> if(missing(y)){y<-3}
> }
>
> But it does not works...
If you don't want to specify the extra arguments for some reason in this
method, then you can process the '...'
func.numeric <- function(x, ...) {
dots <- list(...)
if(!("y" %in% names(dots))) {
y <- 3
} else {
y <- dots[["y"]]
}
return(x + y)
}
> func.numeric(x = 3)
[1] 6> func.numeric(x = 3, y = 10)
[1] 13
> I precise that I can not put 'y' explicitly in the argument list
since
> func is an S3 function, I cannot change its arguments.
You can, as long as you include all the arguments of the generic:
foo <- function(x, ...) {
UseMethod("foo")
}
foo.numeric <- function(x, y, ...) {
return(x + y)
}
> foo(x = 3, y = 10)
[1] 13
HTH
G
> Any suggestions?
>
> Thanks
> Christophe
>
> ______________________________________________
> 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.
--
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
Dr. Gavin Simpson [t] +44 (0)20 7679 0522
ECRC, UCL Geography, [f] +44 (0)20 7679 0565
Pearson Building, [e] gavin.simpsonATNOSPAMucl.ac.uk
Gower Street, London [w] http://www.ucl.ac.uk/~ucfagls/
UK. WC1E 6BT. [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%