How to silently load the packages in R

   When we load the packages for the first time, R shows loading and warning messages on the screen. It is possible to turn off those messages and silently load in packages in R scripts. Here I will show some of the ways to do this.
   Let's load  the 'spam' package in RStudio.

> library(spam)
Loading required package: dotCall64
Loading required package: grid
Spam version 2.1-1 (2017-07-02) is loaded.
Type 'help( Spam)' or 'demo( spam)' for a short introduction 
and overview of this package.
Help for individual functions is also obtained by adding the
suffix '.spam' to the function name, e.g. 'help( chol.spam)'.

Attaching package: ‘spam’

The following objects are masked from ‘package:base’:

    backsolve, forwardsolve

Warning messages:
1: package ‘spam’ was built under R version 3.4.1 
2: package ‘dotCall64’ was built under R version 3.4.1 

  I confirmed the information but I don't want to see on the screen next time when I run my R script. We'll turn off those messages by adding some of the parameters into the library() function. We can implement several methods to do it. We'll see some of them below.

1. Adding some options in library function like below

> library(spam, warn.conflicts = F, quietly = T)
Spam version 2.1-1 (2017-07-02) is loaded.
Type 'help( Spam)' or 'demo( spam)' for a short introduction 
and overview of this package.
Help for individual functions is also obtained by adding the
suffix '.spam' to the function name, e.g. 'help( chol.spam)'.
Warning messages:
1: package ‘spam’ was built under R version 3.4.1 
2: package ‘dotCall64’ was built under R version 3.4.1
> 

We could turn off some of them only.

2. Using the suppressMessages function.

> suppressMessages(library(spam, warn.conflicts = F, quietly = T))
Warning messages:
1: package ‘spam’ was built under R version 3.4.1 
2: package ‘dotCall64’ was built under R version 3.4.1
> 

We have turned off most of the messages but, still warning messages are coming.

3. Finally, we'll add the suppressWarnings function.

> suppressMessages(suppressWarnings(library(spam,warn.conflicts = F, quietly = T)))
or simply,
> suppressMessages(suppressWarnings(library(spam)))
>

We have cleaned all messages in a loading and the package was loaded silently.

Thank you for reading!

2 comments:

  1. Thank you for sharing. It works!!

    ReplyDelete
  2. Seems inane to need to use two functions to actually make the loading quiet.

    ReplyDelete