LJB
LJB

Reputation: 363

Function that returns a function in R

I'm trying to create a function that creates and returns a new function. I've tried the following, but it doesn't work. I want

myfunc <- function(W){

myfunc2=function(X){
Y=W%*%X
return(Y)
}
return(myfunc2)
}

I want to be able to use myfunc2 outside of myfunc. Any ideas of how to do this?

Upvotes: 6

Views: 7610

Answers (2)

Oliver Keyes
Oliver Keyes

Reputation: 3304

Er. Yes it does. From my terminal:

> myfunc <- function(W){
+     
+     myfunc2=function(X){
+         Y=W%*%X
+         return(Y)
+     }
+     return(myfunc2)
+ }
> myfunc()
function(X){
    Y=W%*%X
    return(Y)
}
<environment: 0x5034590>

I mean, if you want to actually be able to call it, you'll need to run as:

myfunc2 <- myfunc()

But other than that it appears to work totally fine. If you want to implicitly assign it to the global environment, instead of having to assign it to an object:

myfunc <- function(W){

    myfunc2=function(X){
        Y=W%*%X
        return(Y)
    }
    assign("name_you_want_in_the_global_environment",myfunc2, envir = .GlobalEnv)
    return(invisible())
}
myfunc()

Upvotes: 9

Zhanxiong
Zhanxiong

Reputation: 140

Just assign the output of myfunc to a function object, say myfunc2. Then you can use it as it was created in global environment.

> myfunc <- function(W){
+ 
+ myfunc2=function(X){
+ Y=W%*%X
+ return(Y)
+ }
+ return(myfunc2)
+ }
> W = diag(2)
> myfunc2 = myfunc(W)
> myfunc2
function(X){
Y=W%*%X
return(Y)
}
<environment: 0x1078a7a38>
> X = diag(2)
> myfunc2(X)
     [,1] [,2]
[1,]    1    0
[2,]    0    1

Upvotes: 1

Related Questions