Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good ways to define functions inside function in R

Tags:

function

r

In R, when want to use one/multiple functions inside another function, maybe there are two ways. An example function can be:

Method 1:

make.power <- function(n) {
 pow <- function(x) {
 x^n
 }
 pow
}

Method 2:

make.power <- function(n) {
     pow(n)
    }

pow <- function(x) {
     x^n
     }

In my opinion (but I am not sure), the second method is a better way if you have lots of child functions for the parent one.

My questions are: 1) Are there any functional differences between the two ways? E.g., how the function will pass variables, or the relationship between the children and parent functions, etc..

2) which one might be a preferred one (maybe more computational efficient or structurally clear) for R?

like image 902
enaJ Avatar asked Aug 27 '15 16:08

enaJ


People also ask

Can you define a function inside a function in R?

The in-built functions in R are powerful, but often in data science we have to create our own functions. Such user-defined functions have a name, argument and a body. For example, the summary function above does not compute the standard deviation. To do this, we can create a user-defined function using the code below.

Is it good practice to define a function inside a function?

It's actually fine to declare one function inside another one. This is specially useful creating decorators. However, as a rule of thumb, if the function is complex (more than 10 lines) it might be a better idea to declare it on the module level.

How do you make a nested function in R?

Nested code: Rather that assigning the output from each step to a separate variable, we could also just nest them into one another. To create a nested function, simply replace the variable name with the code on the right hand side of the assignment operator. Don't forget to keep track of the sets of parentheses!

How do you use a function inside a function?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.


1 Answers

If you are asking about the specific example you gave, this question does not seem too broad to me.

The main difference here is the evaluation of n. For example 1, the function that gets returned will essentially have a hard-coded n value.

> n = 100
> f1 = make.power(2)
> f1(2)
[1] 4
> n = 1
> f1(2)
[1] 4

Example 2 will not, instead it will rely on the global definition of n.

> n = 1
> make.power2(2)
[1] 2
> n = 100
> make.power2(2)
[1] 1.267651e+30

As functions get more complex, so will the scoping issues. The link David Robinson provides in the comments is a great resource.

like image 151
Señor O Avatar answered Oct 15 '22 08:10

Señor O