简体   繁体   English

在R中使用嵌套函数的高效代码

[英]Efficient code using nested functions in R

I am wondering what is more efficient in R when it comes to using nested functions. 我想知道在使用嵌套函数时R中更有效的方法是什么。 Essentially, I have three functions f1, f2, f3. 本质上,我有三个功能f1,f2,f3。 f3 uses f2 which itselfs uses f1 f3使用f2,而f2本身使用f1

The 2 options I have are: 我有2个选项:

  • Define f1, f2, f3 independently. 分别定义f1,f2,f3。 Then use f3 which will use f1 and f2 pre-defined in the environment 然后使用f3,它将使用环境中预定义的f1和f2
  • Define f3, and include f1 and f2 as part of the code of f3, then use f3 定义f3,并将f1和f2作为f3代码的一部分,然后使用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: 我仅使用2个函数f1和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 尽管我不确定这个例子是否可靠...因为它很快

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM