Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in R Programming by (5.3k points)

I've created a utility R script, util.R, which I want to use from other scripts in my project. What is the proper way to ensure that the function this script defines are available to function in my other scripts?

I'm looking for something similar to the require function, that loads a package only if it has not been loaded yet. I don't want to call source("util.R") because that will load the script every time it is called.

I know that I will get some answers telling me to create a package, as in Organizing R Source Code :) But I'm not creating something that will be used elsewhere, it is just a standalone project

1 Answer

0 votes

You can use the exists function from the base package to look for an R object of the given name and possibly return it.

 For example:

  if(!exists("fun", mode="function")) source("util.R")

The above code will check if any function from the source script already exists or not and then accordingly run the script.

Browse Categories