Linus Larsson

Running initial code only once in R script

This script helped me a lot once I figured it out. When I work in R I usually split different functions in different script files and then import them to the "main" script, but if you do this you don't want  to import all functions each time you run the script. So how can you solve this and still be able to run the entire script every time?

It's really super easy. Just create an IF statement where you check if a variable exists. Since it's the first time you run the script the variable obviously won't exist. When the code inside the IF statement runs it will create the varaible on the last line. This ensures that the IF statement won't run again until you clear the environment or the specific variable.

# Created by Linus Larsson
# 2018-12-10
# A simple function to put in the start of your script which will only run the first time you run the script.
# The if statement looks for a variable that does not exist but after the code has run it will define the variable
# and therefore not run again. 
if(exists("hasRun") == FALSE){
  # Examples of what you only want to run once
  hasRun <- TRUE 


Leave a Reply

Your email address will not be published. Required fields are marked *


Cookie Settings

© Copyright - - 2018-2024