[R] specifying arguments in functions and calling functions, within functions

Rui Barradas ruipbarradas at sapo.pt
Wed Sep 26 20:51:49 CEST 2012


Hello,

You define a 2nd version of Scale with the dots argument but do not use it.


Scale2 <- function(x, method=c("mean", "median"),...) {
    scl <- match.fun(method)
    scl(x, ...)   # Here!
}

Scale2(ex, method=median, na.rm=TRUE)  # both return
Scale2(ex, method="median", na.rm=TRUE)  # the median

You could also use 'na.rm = TRUE' instead of '...', since both mean and 
median use it. Anyway, if you define a function with certain arguments, 
do try to use them in the function body. :)

As for the method argument, when the default value is a vector, it's 
primary use is to check that one of those vector values and _only_ one 
of those is passed to the function. More or less like this.

Scale3 <- function(x, method=c("mean", "median"),...) {
    method <- match.arg(method)
    scl <- match.fun(method)
    scl(x, ...)
}

Scale3(ex, method=median, na.rm=TRUE)  # Error
Scale3(ex, method="median", na.rm=TRUE)  # Right
Scale3(ex, method="var", na.rm=TRUE)  # Other type of error


Hope this helps,

Rui Barradas

Em 26-09-2012 16:56, K. Brand escreveu:
> Esteemed R UseRs,
>
> Regarding specifying arguments in functions and calling functions
> within functions:
>
> ## beginning ##
> ## some data
> ex <- rnorm(10)
> ex[5] <- NA
>
> ## example function
> Scale <- function(x, method=c("mean", "median")) {
>     scl <- method
>     scl(x)
> }
>
> ## both return NA
> Scale(ex, method=median)
> median(ex, na.rm=FALSE)
>
> ## both return the median
> Scale(ex, method="median")
> median(ex, na.rm=TRUE)
>
> ## 1. Why does the use of apostrophes have this effect when calling
> ## a fucntion within a function?
>
> ## 2. What's the canonical use of apostrophes in functions like the above:
> ## Scale <- function(x, method=c("mean", "median")) {....
> ## or
> ## Scale <- function(x, method=c(mean, median)) {....
>
> ## 3. How does one specify the arguments of a function being called
> ## within a function? i.e. i thought the use of '...' might work in
> ## the following but i was wrong.
>
> ## '...' has no apparent effect
> Scale <- function(x, method=c("mean", "median"),...) {
>     scl <- method
>     scl(x)
> }
>
> ## both return NA
> Scale(ex, method=median, na.rm=TRUE)
> Scale(ex, method=median, na.rm=FALSE)
> ## end ##
>
>
> I failed to comprehend anything google returned when trying to
> understand this myself. Greatly appreciate any thoughts &/or
> examples on this.
>
> Tia, Karl
>




More information about the R-help mailing list