Search code examples
rrstudiowindows-task-schedulerr-taskscheduler

Using Variables that are Not in the Enviornment of the Task Scheduler R


I am creating an Rscript that will run every 30min via the taskscheduleR package. However, there are variables that need to be updated every 30 min and some variables that should only be updated once a week. I would like the variables that are part of the weekly scheduling to still be in the global environment. For example

#Define a variable x that gets run once per week.
x = 10

#Define a variable y that gets run every thirty minutes. 
y = x*5
print(y)

It seems I might need 2 scripts where the first script I write the data to a csv and then read it in on the script that runs every 30 min. I was wondering if there was a way to do this all on one script thank you.

#script_OnceAweek.R
x = 1:10
write.csv(x, "file.csv")

#script_Every30min.R
k = read.csv("file.csv")
y = k*5

Solution

  • As far as I know, there is no way to differentiate on the execution time of certain lines within the same file since you schedule tasks per file that should be run.

    But I might be able to make the exchange of data between the different files a bit easier.

    When you only have one data object to exchange between scripts:

    #script_OnceAweek.R
    x = 1:10
    saveRDS(x, file = "file.csv")
    
    #script_Every30min.R
    k = readRDS("file.csv")
    y = k*5
    

    If you have multiple data objects:

    #script_OnceAweek.R
    x = 1:10
    y = 4:6
    save(x, y, file = "file.csv")
    
    #script_Every30min.R
    load("file.csv")
    k = x
    y = k*5
    

    The first solution will save to a .RDS file and the second will save to .Rdata file.

    The nice thing about this is that you can save all R data types and also load them as R data types. This means that you could even save objects like lists of data frames for instance.

    When you would use csv's for this, it would become very complicated.