6

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?

LJB
  • 353
  • 4
  • 10
  • I think this question is more appropriate for the programming section, StackOverfow, since it's not a stats question per se. –  Dec 23 '14 at 23:44

2 Answers2

9

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()
Oliver Keyes
  • 3,294
  • 2
  • 14
  • 23
  • Any way to do it without running "myfunc2 <- myfunc()"? I was trying make it so that all I had to do was run "myfunc(W)" and then "myfunc2" would be defined globally. – LJB Dec 24 '14 at 17:01
1

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
Zhanxiong
  • 140
  • 6