Make a user-created function in R

stuppie picture stuppie · Jan 18, 2013 · Viewed 37k times · Source

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?

Answer

Josh O&#39;Brien picture Josh O'Brien · Jan 18, 2013

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.