Site icon R-bloggers

Storing a Function in a Separate File in R

[This article was first published on Mollie's Research Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
If you’re going to be using a function across several different R files, you might want to store the function in its own file.

If you want to name the function in its own file

This is probably the best option in general, if only because you may want to put more than one function in a single file.

Next, let’s make our function in the file fun.R:
mult <- function(x, y) {
    x*y
}
If you get the warning message “In readLines(file) : incomplete final line found on ‘fun.R'”, just insert a line break at the end of the fun.R file.

If you want to name the function in the file running it

First let’s make the same function (but this time unnamed) in the file times.R:
function(x, y) {
    x*y
}

Calling the functions

And finally we’ll make a file file.R to call our functions:
times <- dget("times.R")
times(-4:4, 2)

source("fun.R")
mult(-4:4, 2)
Note: if you are used to using source to run your R code, note that in this case we are using the source command within a file.


All files are available as a gist.

To leave a comment for the author, please follow the link and comment on their blog: Mollie's Research Blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.