Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the function()-function in R "not" require curly brackets?

Tags:

I recently encountered this example in my R tutorial:

sapply(list(runif (10), runif (10)), 
   function(x) c(min = min(x), mean = mean(x), max = max(x))

I was under the impression that in the function()-function you first had to list your arguments within parenthesis and then the actions performed by the function inside curly brackets.

In this example there are "no" curly brackets and the code seems to function anyway, how can this be?

like image 864
Magnus Avatar asked May 31 '19 20:05

Magnus


1 Answers

It is a single statement and for that there is no need for any brackets

sapply(0:5, function(x) x  + 5)

But, if the function demands multiple statements, each statement can be separated within the curly brackets

sapply(0:5, function(x) {
             x <- sequence(x)
             x1 <- x[x > 2]
             c(mean = mean(x1), min = min(x1))
             })

As @qdread mentioned in the comments, a good practice would be to include the curlies though there might be a slight efficiency dip

library(microbenchmark)
microbenchmark(nocurly = sapply(0:1e6, function(x) x + 5),
      curly = sapply(0:1e6, function(x) {x + 5}))
#Unit: milliseconds
#    expr      min       lq     mean   median       uq      max neval
# nocurly 666.2539 922.0929 928.6206 942.9065 966.8318 1113.828   100
#   curly 710.8450 925.7917 947.7641 955.2041 973.8009 1081.597   100
like image 64
akrun Avatar answered Oct 19 '22 05:10

akrun