Function parameter as argument in an R function
Asked Answered
F

3

10

I am attempting to write a general function to calculate coverage probabilities for interval estimation of Binomial proportions in R. I intend to do this for a variety of confidence interval methods e.g. Wald, Clopper-Pearson, HPD intervals for varying priors.

Ideally, I would like there to be one function, that can take, as an argument, the method that should be used to calculate the interval. My question then: how can I include a function as an argument in another function?

As an example, for the Exact Clopper-Pearson interval I have the following function:

# Coverage for Exact interval
ExactCoverage <- function(n) {
p <- seq(0,1,.001)
x <- 0:n

# value of dist
dist <- sapply(p, dbinom, size=n, x=x)

# interval
int <- Exact(x,n)

# indicator function
ind <- sapply(p, function(x) cbind(int[,1] <= x & int[,2] >= x))

list(coverage = apply(ind*dist, 2, sum), p = p)
}

Where Exact(x,n) is just a function to calculate the appropriate interval. I would like to have

Coverage <- function(n, FUN, ...)
...
# interval
int <- FUN(...)

so that I have one function to calculate the coverage probabilities rather than a separate coverage function for each method of interval calculation. Is there a standard way to do this? I have not been able to find an explanation.

Thanks, James

Fabio answered 22/3, 2013 at 9:33 Comment(1)
You might want to read github.com/hadley/devtools/wiki/Functional-programmingMalachi
M
16

In R, a function can be provided as a function argument. The syntax matches the one of non-function objects.

Here is an example function.

myfun <- function(x, FUN) {
  FUN(x)
}

This function applies the function FUN to the object x.

A few examples with a vector including the numbers from 1 to 10:

vec <- 1:10 

> myfun(vec, mean)
[1] 5.5
> myfun(vec, sum)
[1] 55
> myfun(vec, diff)
[1] 1 1 1 1 1 1 1 1 1

This is not limited to built-in functions, but works with any function:

> myfun(vec, function(obj) sum(obj) / length(obj))
[1] 5.5

mymean <- function(obj){
  sum(obj) / length(obj)
}
> myfun(vec, mymean)
[1] 5.5
Maltzman answered 22/3, 2013 at 9:47 Comment(2)
How would you add function parameters for the passed function "FUN"?Superconductivity
This is really late @Christian, but for others: ``` myfun <- function(x, FUN, ...) { FUN(x, ...) } ```Motet
T
2

you can also store a function name as a character variable, and call it with do.call()

> test = c(1:5)
> do.call(mean, list(test))
[1] 3
> 
> func = 'mean'
> do.call(func, list(test))
[1] 3
Tannate answered 22/11, 2015 at 6:2 Comment(0)
M
0

Hadley's text gives a great (and simple) example:

randomise <- function(f) f(runif(1e3))

randomise(mean)
#> [1] 0.5059199
randomise(mean)
#> [1] 0.5029048
randomise(sum)
#> [1] 504.245
Mystique answered 3/7, 2020 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.