简体   繁体   中英

Efficient code using nested functions in R

I am wondering what is more efficient in R when it comes to using nested functions. Essentially, I have three functions f1, f2, f3. f3 uses f2 which itselfs uses f1

The 2 options I have are:

  • Define f1, f2, f3 independently. Then use f3 which will use f1 and f2 pre-defined in the environment
  • Define f3, and include f1 and f2 as part of the code of f3, then use f3

To your knowledge, is one of these ways more efficient than the other?

Many thanks

Thank you. I didn't know this function. I ran the following using only 2 functions f1 and f2:

f1 <- function(x) {
  y <- x + 2
  return(y)
}

f2 <- function(y){
  x = 3
  z <- y + 3 + f1(x)
  return(z)
}

Which returned

> microbenchmark::microbenchmark(f2(2))
Unit: nanoseconds
expr min  lq     mean median    uq     max neval
f2(2) 737 754 47665.41  798.5 910.5 4667754   100

As opposed to

f3 <- function(y){

  f4 <- function(x) {
  y <- x + 2
  return(y)}

  x = 3
  z <- y + 3 + f4(x)
  return(z)
}

Which seems a bit slower

> microbenchmark::microbenchmark(f3(2))
Unit: nanoseconds
  expr min    lq     mean median   uq     max neval
 f3(2) 844 868.5 53053.53   1000 1096 5180886   100

Although I'm not sure this example is very reliable... as it is very quick

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