简体   繁体   中英

Is it possible to define a function as an argument of another function in R?

for example:

method1 <- function(alpha,beta,ff)

Does R allow this ???

What I am try to achieve is that: I have a general method, method1 . And I have other methods: f2,f3,f4 . I want it to be like method1 <- function(a,b, ff) , where a & b are constants and most importantly, ff can be either f2 or f3 or f4 , depending on how i call the function on the console. Ideally f2, f3, f4 computes a matrix.

Using the example in your answer below, I was wondering why cant I have this instead??

f1 <- function(a,b,ff(a,b))
{
    solve(ff(a,b))
}
f2 <- function (x,y){
    Diag(x*y)
}

This is a really bad example. But I would like to know why cant I include the ff(a,b) in the argument ??? What is the logic of writing ?

f1 <- function(a,b,ff){ ff(a,b) }

Depends what you mean. You can pass a function as an argument to another function, and you can make the default argument a function:

f <- function(a,b,f2=function(x,y) { x+y}) {
   f2(a,b)
}
f(1,2) ## 3

You can pass the results of a function call:

f <- function(a,b,c) { a + b + c }
f3 <- function(x,y) { x*y }
f(1,2,f3(3,4))

But you can't do exactly what you specified: arguments must be named according to the standard variable-naming conventions (see ?make.names ).

f <- function(a,b,f2(1,3)) { ... ## error

You can do it by using backticks, or by assigning names(formals(f))[3] <- "f2(1,3)" , but that's dangerous and probably not what you wanted.

function(a,b,`f2(1,3)`) { }

If you explain a little more of the context of what you're trying to do you might get a more meaningful answer ...

edit : taking a guess based on your description, you want the first thing I described above.

f1 <- function(a,b,ff) {
   ff(a,b) 
}
f2 <- function(x,y) diag(x)*y
f3 <- function(x,y) matrix(runif(x*y),nrow=x,ncol=y)
f4 <- function(x,y) outer(seq(x),seq(y))
f1(2,2,f2)
##      [,1] [,2]
## [1,]    2    0
## [2,]    0    2
f1(2,2,f3)
##             [,1]       [,2]
## [1,] 0.773723089 0.09640121
## [2,] 0.006206349 0.84351541
f1(2,2,f4)
##      [,1] [,2]
## [1,]    1    2
## [2,]    2    4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM