Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include library calls in functions?

Tags:

r

Is it good practice to include every library I need to execute a function within that function?

For example, my file global.r contains several functions I need for a shiny app. Currently I have all needed packages at the top of the file. When I'm switching projects/copying these functions I have to load the packages/include them in the new code. Otherwise all needed packages are contained in that function. Of course I have to check all functions with a new R session, but I think this could help in the long run.

When I tried to load a package twice it won't load the package again but checks it's already loaded. My main question is if it would slow my functions if I restructure in that way?

I only saw that practice once, library calls inside functions, so I'm not sure.

like image 900
Sebastian Avatar asked Mar 29 '16 12:03

Sebastian


1 Answers

As one of the commenters suggest, you should avoid loading packages within a function since

  1. The function now has a global effect - as a general rule, this is something to avoid.
  2. There is a very small performance hit.

The first point is the big one. As with most optimisation, only worry about the second point if it's an issue.

Now that we've established the principle, what are the possible solution.

  1. In small projects, I have a file called packages.R that includes all the library calls I need. This is sourced at the top of my analysis script. BTW, all my functions are in a file call func.R. This workflow was stolen/adapted from a previous SO question

  2. If you're only importing a single function, you could use the :: trick, e.g. package::funcA(...) That way you avoid loading the package.

  3. For larger projects, I create an R package that handles all necessary imports. The benefit of creating a package is detailed in this answer on structuring large R projects.

like image 199
csgillespie Avatar answered Nov 08 '22 10:11

csgillespie