1

During my free time R studying, I read this article on usage of return(). In there, I came across a function, of which one element's meaning escapes my technical background, please see below:

bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return 
(function(x)vector(length=x,mode="numeric"))(x),repeats)) }

I've played with the codes of the article, but the logic behind this tiny (x) (specifically, it's 2nd occurrence) in the 3rd line is unclear to me.

Pittoro
  • 83
  • 6
  • `x` in this context is a argument passed into the `bench_nor2` function. For instance, if you called that function by writing `bench_nor2(54,3)` then `x =54` – Daniel O May 04 '20 at 11:49

1 Answers1

0

It's an anonymous function. If we unwrap the code

bench_nor2 <- function(x,repeats) { system.time(rep(
  # without explicit return 
   (function(x) 
      vector(length=x,mode="numeric")
   )(x),  
  repeats)) }

we can see that within the rep( ... ) call, the first argument is

(function(x)vector(length=x,mode="numeric"))(x)

Now, this is a curious way of putting it. But what you get is that function(x) vector(...) defines a one-liner function (which calls vector to create a numeric vector of length x). Wrapped in parenthesis (function(x) ...) returns the function, and then with (function(x) ...)(x) calls the anonymous function with argument x.

You would get the same result from:

my_vector <- function(y) vector(length=y, mode="numeric")
bench_nor2 <- function(x, repeats) {system.time(rep(my_vector(x), repeats))}
MrGumble
  • 5,631
  • 1
  • 18
  • 33