启动时加载包 [英] Load package at start-up

查看:66
本文介绍了启动时加载包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在启动时加载一个已经安装的包.如果不是,那么我想先安装它,然后加载它.所以,我创建了以下函数:

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)
}

这在 RStudio 被打开后效果很好,但在启动时就不太适用了.我将此函数添加到我的本地 .RProfile 文件中:

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"

一个选择是手动安装包,然后添加一堆library("xyz")

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.

我有两个问题:

1) 有人可以帮我吗?

2) 有没有更有效的方法?

我的帖子灵感来自以下两个链接:1) 在运行 install.packages() 之前检查已安装的包2) http://www.statmethods.net/interface/customizing.html

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

我很感激任何帮助.

谢谢

推荐答案

好的.这段代码有效:

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.

这篇关于启动时加载包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆