rrdata

.RData objects seem to disappear, affecting my cron jobs


I have a cron job running an R script that checks the values of certain variables and sends an email depending on said values (with an if-statement), then it will alter the value, the cronjob runs every 5 minutes indefinitely, however the cron will only work after the first instance of the if-statement being satisfied. After that it seems the objects disappear from the workspace and therefore causes the script to fail:

load("/home/ec2-user/R_Scripts/.RData") # the objects load successfully the first time

print("CURTAILING $200:")
print(curtailing_200) # this is where the fail occurs, it says the object cannot be found after the first entrance into the if-statement, as per my cron logs
print("LAST DECISION $200:")
print(last_decision_200)
print("SMP LENGTH $200:")
length(smp_vec)
print("SMP VEC $200:")
mean(smp_vec)



if ((length(smp_vec) == 31) && (mean(smp_vec) > 200) && (curtailing_200 == FALSE) && (now >= last_decision_200 )) { #send curtailment notice if we are in the 30th minute and conditions are met
  print("IF")
  curtailment_start_200()
  curtailing_200 = TRUE # here I reassign a new value
  last_decision_200 = now # here I assign a new value
  save(curtailing_200, file="/home/ec2-user/R_Scripts/.RData") 
  save(last_decision_200, file="/home/ec2-user/R_Scripts/.RData")
  save.image() # save the values
}

Sorry if this sounds confusing, but basically the objects are loaded fine, until the if-statement gets satisfied eventually, then inside the if-statement I alter the objects and save them (seemingly). Then after that it seems the objects are gone.


Solution

  • save() saves one or more objects in a file, but it cannot update an existing file. save.image() writes all your objects to a file, but since you are not specifying its location my guess is it ends up in the wrong place.

      save(curtailing_200, file="/home/ec2-user/R_Scripts/.RData")
      ## saves one object
    
    
      save(last_decision_200, file="/home/ec2-user/R_Scripts/.RData") 
      ## overwrites the previous object with this one
    
    
      save.image() 
      ## if this goes to the same place, it will overwrite the previous line
      ## but since R can't find the objects after load()
      ## it probably is going to the wrong folder
    

    Replace those 3 lines above with

    save.image(file = "/home/ec2-user/R_Scripts/.RData")