简体   繁体   中英

Function (defined by user) as argument of a function

I would like to write a function where one of the argument is a function written by the user.

Specifically, I have something like:

My_function(n,g){
    x<-dnorm(n,0,1)
    y<-g(x)
    return(y)
}

For example, g(x)=x^2 ... but is chosen by the user. Of course, I could directly put g(dnorm(n,0,1)) as argument but I would like the user to write it in terms of x, ie g<-x^2 in the example.

How could I do this since the x object is only defined within the function (and not in the arguments)

I can't define the g function beforehand (otherwise, I reckon it's easy). It has to be defined within "My_function" so that the user defines everything he needs in one line.

Why not just declare g as a function with argument?

g=function(x) x^2

My_function=function(n,g){
    x<-dnorm(n,0,1)
    y<-g(x)
    return(y)
}

My_function(1,g)

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