Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are sapply() and options() "undesirable"?

Tags:

r

sapply

lintr

Jim Hester's "lintr" package contains many different linters for R. The README for the package describes one of the linters in this way:

undesirable_function_linter: report the use of undesirable functions, e.g. options or sapply and suggest an alternative.

I was surprised. I've been using R for many years, and I've been using options() and sapply() for many years. What makes them undesirable? And are there better alternatives?

I know about getOption(), but it's not a substitute for options(). I also know about the *apply() variants, Map(), and the Tidyverse map functions. The Tidyverse functions do seem better to me on the whole than sapply() or Map() -- I prefer the defaults and the ordering of arguments in the Tidyverse functions -- but I wouldn't have thought to call sapply() "undesirable."

like image 628
user697473 Avatar asked Mar 01 '23 19:03

user697473


1 Answers

If you look at the header for that function,

function(fun = default_undesirable_functions)

you see that it records its choices in default_undesirable_functions, and if you look at that object, you'll see:

...
$options
[1] "use withr::with_options()"
...
$sapply
[1] "use vapply() or lapply()"
...

From the alternatives, you can guess at why the author thinks those functions are "undesirable":

  • options() is bad because it has global side effects. The withr::with_options() alternative keeps any changes to the options local.
  • sapply() is bad because vapply() is safer (as documented in ?sapply).
like image 84
user2554330 Avatar answered Mar 05 '23 00:03

user2554330