3

Looked around and still not sure what is the difference between library()/require() and source() in r? According to this SO question: What is the difference between require() and library()? it looks like library() and require() are the same thing, maybe one is legacy. Is source() for lazy developers that don't want to create a library? When do you use each of these constructs?

Denis
  • 11,796
  • 16
  • 88
  • 150
  • The main difference between `library` and `require` is explained in the top answer to the linked question. So, they are not the same. Personally, I never use `source` explicitly, only implicitly via the IDE. You use it to run a script. – Roland Mar 12 '19 at 13:26

2 Answers2

4

source runs the code in a .R file, line by line.

library and require load and attach R packages.

Is source() for lazy developers that don't want to create a library?

You're correct that source is for the cases when you don't have a package. Laziness is not the only reason, sometimes packages are not appropriate---packages provide functionality, but don't do things. Perhaps I have a script that pulls data from a database, fits a model, and makes some predictions. A package may provide functions to help me do that, but it does not actually do it. A script saved in a .R file and run with source() could run the commands and complete the task.


I do want to address this:

it looks like library() and require() are the same thing, maybe one is legacy.

They both do the same thing (load and attach a package). The main difference is that library() will throw an error and stop the script if the package is not available, whereas require() will return TRUE or FALSE depending on its success. The general consensus is that library is better so that your script stops with a nice clear error and you can install the missing package before proceeeding. The question linked has a more thorough discussion which I won't try to replicate here.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
4

The differences between library and require are already well documented in What is the difference between require() and library()?.

So, I will focus on how source differs from these. In fact they are fundamentally quite different commands. Neither library nor require actually execute any code. They simply attach a namespace, in a lazy fashion, meaning that individual functions in the package are not run unless they are actually called later. Source on the other hand does something quite different which is to execute all of the code in the file at that time.

A small caveat: packages can be made to actually run some code at the time of package loading or attaching, via the .onLoad and .onAttach functions. Have a look here: https://stat.ethz.ch/R-manual/R-devel/library/base/html/ns-hooks.html

dww
  • 30,425
  • 5
  • 68
  • 111