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
# https://lynuhs.com/
# 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
  source("functions.R") 
  library(ggplot2)
  
  hasRun <- TRUE 
}

Comments

Comments are currently not available due to roll out of custom built blog theme. I'm working on getting this available again, but in the mean time you can write to me on LinkedIn if you have any questions.

© Copyright - Lynuhs.com - 2018-2021