Home > front end >  How to conveniently install uninstalled packages found in library() calls in a script in RStudio?
How to conveniently install uninstalled packages found in library() calls in a script in RStudio?

Time:01-10

Suppose I'm given a script with a bunch of packages, some of which I already have installed and others I don't, is there a quick/easy way (keyboard shortcut perhaps?) to make RStudio 1. recognise the library() calls, and 2. install any packages that aren't already installed?

Note: I recall a small notification used to appear toward to the top of the RStudio script pane, but it doesn't seem to happen for me -- perhaps that feature was removed or I need to do something to trigger it.

An example of a script with a lot of library() calls:

library(shiny) # not installed
library(shinydashboard) # not installed
library(dplyr) # already installed
library(tm) # etc etc
library(wordcloud)
library(memoise)
library(janeaustenr)
library(tidyverse)
library(tidytext)
library(wordcloud2)
library(tidyr)
# Truncated for brevity 

CodePudding user response:

Well, I found one way is to save the script, that will trigger the notification offering to install uninstalled packages:

enter image description here

CodePudding user response:

Define your own library function which checks if the package is installed and if not installs it.

require loads the package if it is present and returns TRUE. It returns FALSE if not present.

library <- function(package, ...) {
  if (!require(package, ...)) {
    install.packages(package);
    base::library(package, ...)
  }
}
  •  Tags:  
  • Related