Load package at start-up

南楼画角 提交于 2019-12-11 23:18:15

问题


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


回答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.



来源:https://stackoverflow.com/questions/38821124/load-package-at-start-up

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!