Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a user-created function in R

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?

like image 535
stuppie Avatar asked Jan 18 '13 16:01

stuppie


1 Answers

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.

like image 188
Josh O'Brien Avatar answered Nov 08 '22 19:11

Josh O'Brien