0

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
TylerH
  • 20,799
  • 66
  • 75
  • 101
Jordan Wrong
  • 1,205
  • 1
  • 12
  • 32

2 Answers2

2

You can check how long ago you updated the weekly CSV first with an if statement. You can use file.info and Sys.time.

info <- file.info("yourfile") Sys.time() - info$mtime

If it’s a week old, update it, if not, skip that step.

Sven
  • 1,203
  • 1
  • 5
  • 14
1

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.

dylanvanw
  • 3,029
  • 1
  • 8
  • 18
  • Thank you very much dylan for taking it one step further. This will do just fine for my purposes (loading multiple lists/variables). – Jordan Wrong Jun 04 '19 at 07:03
  • Happy to help. Also take a look at @Sven his answer, looks like this could be what you were looking for. – dylanvanw Jun 04 '19 at 07:11