Ixxie
Ixxie

Reputation: 1473

Startup script in Rprofile throws 'function not found' errors

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.

Upvotes: 2

Views: 448

Answers (2)

Ricardo Saporta
Ricardo Saporta

Reputation: 55360

The reason for the error is that when .First() the packages are not yet loaded.

Although runif and rnorm might seem like default functions, they are actually part of the stats package. And as such, they are NOT available when .First() is called (unless you specifically call that package from within .First)

... which also explains this:

When I load the same file manually into the workspace I get no errors.

After .First() but before you have the chance to run anything manually, the default packages are attached. And hence available to your functions when you call it manually.


The solution is to create a file (if it does not already exist) called "~/.Rprofile" and put in there the lines you currently have in .First()

Upvotes: 1

Carl Witthoft
Carl Witthoft

Reputation: 21502

You don't need (or, really, want) to create a .First . If you put those lines into your .Rprofile they'll execute just fine. -- With the proviso @Pascal pointed out, that any function called in your file.R must have its library loaded first. So, near the bottom of your .Rprofile, just put

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

EDIT: I cannot reproduce your problem. I added these lines to the end of my .Rprofile:

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

And the console returns ten nice numbers.

Upvotes: 1

Related Questions