6

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."

miken32
  • 42,008
  • 16
  • 111
  • 154
user697473
  • 2,165
  • 1
  • 20
  • 47
  • 3
    `sapply` "... tries to simplify the result, so it can return a list, a vector, or a matrix. This makes it difficult to program with, and it should be avoided in non-interactive settings." See https://adv-r.hadley.nz/functionals.html?q=sapply#map-atomic. – stefan Dec 27 '20 at 13:45
  • 5
    Use `vapply` instead of `sapply`. – Roland Dec 27 '20 at 13:46

1 Answers1

9

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).
user2554330
  • 37,248
  • 4
  • 43
  • 90