Skip to content

Running initial code only once in R script

0
(0)

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
# http://34.78.24.69

# 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 
}

How useful was this post?

Average rating 0 / 5. Vote count: 0

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Published inR

Leave a Reply

Lynuhs