0

I am trying to load a package at start-up if it's already installed. If it isn't then I want to first install it and then load it. So, I created the following function:

RLoadPackage <- function(packname)
{
  if((packname %in% rownames(installed.packages()))==FALSE)
  {
    install.packages(packname,dependencies = TRUE)
  } 
  library(packname,character.only = TRUE)
}

This works well once RStudio is opened, but it doesn't quite work at start-up. I added this function to my local .RProfile file as:

RLoadPackage("ggplot2")

RLoadPackage <- function(packname)
{
  if((packname %in% rownames(installed.packages()))==FALSE)
  {
    install.packages(packname,dependencies = TRUE)
  } 
  library(packname,character.only = TRUE)
}

However, I get the error message as:

Error: could not find function "RLoadPackage"

One option is to install packages manually and then add a bunch of library("xyz")

However, the above option is very clunky. So, I created a function.

I've 2 questions:

1) Can someone please help me with it?

2) Is there more efficient way of doing this?

My post is inspired from the following two links: 1) Check for installed packages before running install.packages() 2) http://www.statmethods.net/interface/customizing.html

I'd appreciate any help.

Thanks

Community
  • 1
  • 1
watchtower
  • 4,140
  • 14
  • 50
  • 92
  • 4
    Check out `help(".First")`. – shayaa Aug 08 '16 at 04:09
  • @Richard Scriven and Shayaa--I believe I read your mind! I just thought that R is sequentially processing functions. So, I defined the function before everything else, and it worked. However, I'm looking for more efficient code--if you are aware of any method to load 10-15 packages and do what I am trying to do. I'd appreciate your help. – watchtower Aug 08 '16 at 04:12
  • 1
    Isn't your "Error: could not find function..." simply due to the fact that you call `RLoadPackage("ggplot2")` before defining `RLoadPackage`? – Choubi Aug 08 '16 at 10:34
  • Yes! that is correct – watchtower Aug 08 '16 at 13:55

1 Answers1

-1

Ok. This piece of code works:

library("utils")

RLoadPackage <- function(packname)
{
  if((packname %in% rownames(installed.packages()))==FALSE)
  {
    install.packages(packname,dependencies = TRUE)
  } 
  library(packname,character.only = TRUE)
}

RLoadPackage("ggplot2")
RLoadPackage("dplyr")
RLoadPackage("lubridate")

However, is there more efficient way of loading multiple packages--maybe a vectorized version of this? I am just curious.

watchtower
  • 4,140
  • 14
  • 50
  • 92