Last active
December 11, 2017 21:38
-
-
Save Dasonk/2b62e333251404d517100c3262ea19fd to your computer and use it in GitHub Desktop.
Function to create a function to use as a taskCallBack to monitor changes in objects easily
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Monitor objects using output | |
#' | |
#' This creates a function that is meant to be used as a taskCallBack. | |
#' You can call the resulting function directly yourself when you want | |
#' to monitor changes but that isn't the intended use. | |
#' | |
#' @param object_name Character string. The object name you want to montior | |
#' @param FUN function - The function used to monitor the object for changes. | |
#' The only time notifications will be messaged is when | |
#' the output from FUN changes. | |
#' @examples | |
#' my_monitor <- monitor_object("mtcars", dim) | |
#' my_monitor() | |
#' mtcars <- mtcars[1:5,] | |
#' my_monitor() | |
#' mtcars <- mtcars[T, ] # no change | |
#' my_monitor | |
#' rm(mtcars) | |
#' | |
#' tc <- addTaskCallback(monitor_object("mtcars", dim)) | |
#' mtcars <- mtcars[1:5,] | |
#' removeTaskCallback(tc) | |
monitor_object <- function(object_name, FUN = dim){ | |
fun_name <- deparse(substitute(FUN)) | |
print(fun_name) | |
object_dim <- NULL | |
if(exists(object_name)){ | |
object_output <- FUN(get(object_name)) | |
} | |
callback_function <- function(...){ | |
new_output <- NULL | |
if(exists(object_name)){ | |
new_output <- FUN(get(object_name)) | |
} | |
if(!identical(new_output, object_output)){ | |
msg <- paste0(object_name, " changed. Summary function: ", fun_name, | |
"\nOld output: ", paste(object_output, collapse = " "), | |
"\nNew output: ", paste(new_output, collapse = " ")) | |
object_output <<- new_output | |
message(msg) | |
} | |
return(TRUE) | |
} | |
return(callback_function) | |
} | |
# tc <- addTaskCallback(monitor_object("mtcars", nrow)) | |
# removeTaskCallback(tc) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment