Question

I'm sorry if this has been asked before but I can't find the answer.

Let's say I write a small function in R

add2<-function(a){
return(a+2)
}

I save it as add2.R in my home directory (or any directory). How do I get R to find it??

> add2(4)
Error: could not find function "add2"

I know I can open up the script, copy/paste it in the console, run it, and then it works. But how do I get it built-in so if I open and close R, it still runs without me copying and pasting it in?

Was it helpful?

Solution

One lightweight option:

dump("add2", file="myFunction.R")

## Then in a subsequent R session
source("myFunction.R")

An alternative:

save("add2", file="myFunction.Rdata")

## Then just double click on "myFunction.Rdata" to open  
## an R session with add2() already in it 

## You can also import the function to any other R session with
load("myFunction.Rdata")

Until you're ready to package up functions into your own private package, storing them in well organized, source()-ready text files (as in the 1st example above) is probably the best strategy. See this highly up-voted SO question for some examples of how experienced useRs put this approach into practice.

OTHER TIPS

Before invoking the function (e.g. at the beginning of the script), you should source the file containing your user defined function/s, i.e. :

source("add2.R") # this executes add2.R script loading add2 function

Basically, source function executes the code included in the script passed as argument. So if the file contains only functions definitions it loads the function in memory for future use.

If you want to start it automatically, then you have to set-up startup script and then use one of the methods outlined in answers above.

/Library/Frameworks/R.framework/Versions/2.15/Resources/etc/ is(for mac) the location of Rprofile.site, which must be edited adequately.

My version of it is:

.First <- function()
{ 
    dir='~/Desktop/Infobase/R/0_init/0_init.R'
    if(file.exists(dir))
    {
    source(dir, chdir = TRUE) 
    } else {cat("startup file is not found at:",dir)}
    cat("\nWelcome at", date(), "\n")
}    

.Last <- function()
{ 
cat("\nGoodbye at ", date(), "\n")
}

Note, that after you have sourced 1 R script, you do not need to enter this file anymore. Just do all you need from the file you sourced. In my case file "0_init.R" contains no functions, it just contains loading of other scripts. Well, you've got the idea.

Also, if you are doing this I recommend you to store them in new environment. Actual environments are not really suitable for your own functions(They are better implemented if you have a package developed, otherwise you lose a lot of control).

use "attach", "detach", "search", etc....

attach(FUN,name="af2tr")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top