2

I want R to load a certain file on initialization, so naturally I added a source command to my Rprofile so:

  .First <- function()
   {
         cat("\n   Welcome to R MotherFnorder!!!\n\n")
         setwd("/home/username/Code/R/")
       source("/home/username/Code/R/file.R")
   }

But now when I start R it throws a 'function not found' error for default functions like runif or rnorm. When I load the same file manually into the workspace I get no errors.

4

2 回答 2

1

错误的原因是.First()尚未加载包时。

虽然runifrnorm可能看起来像默认函数,但它们实际上是stats包的一部分。因此,它们在被调用时不可用.First()(除非您专门从内部调用该包.First

...这也解释了这一点:

当我手动将相同的文件加载到工作区时,我没有收到任何错误。

在您有机会手动运行任何内容之后.First()之前,会附加默认软件包。因此,当您手动调用它时,它可用于您的功能。


解决方案是创建一个名为的文件(如果它不存在) "~/.Rprofile"并将您当前拥有的行放入其中.First()

于 2014-08-27T01:29:30.473 回答
1

你不需要(或者,真的,想要)创建一个.First. 如果您将这些行放入您的行中.Rprofile,它们将执行得很好。- 附带条件@Pascal 指出,在您调用的任何函数file.R都必须首先加载其库。所以,在你的底部附近.Rprofile,把

library(whatever_packages_needed)
cat("\n   Welcome to R MotherFnorder!!!\n\n")
setwd("/home/username/Code/R/")
source("/home/username/Code/R/file.R")

编辑:我无法重现您的问题。我将这些行添加到 .Rprofile 的末尾:

#testing SO problem with libloading
library(stats)
runif(10)

控制台返回十个不错的数字。

于 2014-06-17T11:54:40.860 回答