Storing a Function in a Separate File in R

January 24, 2013
By

(This article was first published on Mollie's Research Blog, and kindly contributed to R-bloggers)

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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



    If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

    Comments are closed.

    Sponsors

    Never miss an update!
    Subscribe to R-bloggers to receive
    e-mails with the latest R posts.
    (You will not see this message again.)

    Click here to close (This popup will not appear again)