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?
R any () Function It takes the set of vectors and returns a set of logical vectors, in which at least one of the value is true. 3.1. Usage of R any () Function Check if any or all the elements of a vector are TRUE. Both functions also accept many objects. … means one or more R objects that need to be checked.
The R return function By default, the R functions will return the last evaluated object inside it. You can also make use of the return function, which is especially important when you want to return one object or another, depending on certain conditions, or when you want to execute some code after the object you want to return.
The following is the syntax for a user-defined function in R: Function_name <- function(arguments){ function_body return (return) } Where function_name is the name of the function, arguments are the input arguments needed by the function, function_body is the body of the function, return is the return value of the function. How to call R function?
For example, the following function returns a string telling whether or not the input number is divisible by three. In case the return statement is not present, R returns the value of the last expression in the function by default. An environment is the collection of all the variables and objects.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With