Search code examples
rcron

Updating the index of a for loop in crontab using R


I have a variable called missing_possid that contains 212 integer values. This variable is the possession ID of each possession in a basketball game. I'm trying to create gganimate generated animations and save that to a gif using make_poss_gif function. I'm trying to run this function in a for loop, as you can see below:

# For loop
for (possid in missing_possid) {

  make_poss_gif(possid)

}

Each iteration takes 1-2 minutes to load, so I'd like to use crontab to execute this task every day. What I'd want is crontab to run the first 10 values on the first day, the next 10 values on the second day, etc...

I've used crontab to run a R script once, but I've never had to deal with the indexes inside a for loop before, so I have no idea where to start!

Thank you!


Solution

  • I suggest you should specify an output directory for your gif files. Each time you start your R file you should check the number of files inside your output directory. Be sure that only your gif files are part of that directory.

    Therefore you could adapt like this...

    ## check number of files already done
    n_files <- length(list.files("Your_output_dir"))
    ## stop if all files are done
    if(length(1:n_files)==length(missing_possid)) {
      print("All files done")
      q()
    }
    ## set which part of missing_possid should be taken
    loop_run <- c((n_files+1):((n_files+1)+9)) 
    ## adapt loop_run if there are less than 10 files left over 
    if((length(1:n_files)+10)>length(missing_possid)){
      loop_run <- loop_run[1:c(length(missing_possid)-(length(1:n_files)))]
    }
    # For loop
    for (possid in loop_run) {
    
      make_poss_gif(missing_possid[possid])
    
    }