Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call R library at beginning of file or before use? [closed]

Tags:

r

libraries

I have been putting all my library calls at the top of my a main R file. But after creating more files, making code more abstract, I'm wondering if I'm doing things wrong. I see benefits both ways:

TOP of file - you get to see everything that is used at once, and as long as you call these once, they are in the environment and you only need call them once

BEFORE USE - code (esp functions and sourced files) are more self-contained, but you may end up calling a library more than once (not sure if that's a problem).

Which is the correct way to call R libraries: at the beginning of a script/file or before use?

like image 324
jpmorris Avatar asked Oct 25 '25 06:10

jpmorris


1 Answers

I don't think there is an 'official' way to do this, but the Google R style guide suggests the following (emphasis mine):

General Layout and Ordering

If everyone uses the same general ordering, we'll be able to read and understand each other's scripts faster and more easily.

Copyright statement comment

Author comment File description comment, including purpose of program, inputs, and outputs

source() and library() statements

Function definitions

Executed statements, if applicable (e.g., print, plot)

This of course, means that library calls should be closer to the top (as in your first option). I guess the main thing is consistency, as Wickham states in his style guide, which doesn't explicitly mentions script structures, but mentions a series of pros to being consistent if your code has many readers.

like image 95
erasmortg Avatar answered Oct 26 '25 21:10

erasmortg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!