Guest User

Untitled

a guest
Oct 19th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. #' A progress bar to use outside of loops.
  2. #'
  3. #' Useful when loading data, sourcing files etc .
  4. #' Prints '+' characters like a regular progress bar,
  5. #' however it saves times between calls and returns a suggestion
  6. #' of new steps once value 100 is reached
  7. #' b(0) initiates the time value in a dedicated environment
  8. #' b(100) (or incremental call reaching 100) advises depending on
  9. #' 3rd argument and removes the variable and environment
  10. #' @param n status or increment, from 0 to 100
  11. #' @param incremental by default we give absolute progress values,
  12. #' set to TRUE to give incremental values
  13. #' @param advise relevant for last step only, give advises better
  14. #' n values for the next time you run your script on similar data
  15. #' @example
  16. #' {
  17. #' b(0);Sys.sleep(2)
  18. #' b();Sys.sleep(1)
  19. #' b();Sys.sleep(1)
  20. #' b(100,a=T)
  21. #' b(00);Sys.sleep(2)
  22. #' b(50);Sys.sleep(1)
  23. #' b(75);Sys.sleep(1)
  24. #' b(100)
  25. #' }
  26. b <- function(n,incremental=FALSE,advise=F){
  27. # default b() will increment 1
  28. if(missing(n)) {
  29. n <- 1
  30. incremental = TRUE
  31. }
  32.  
  33. # initialize environment and value, or update time vector
  34. if(n == 0) {
  35. assign(".adhoc_pb_env",new.env(),envir=globalenv()) # <- THIS IS WHAT I DON'T LIKE
  36. .adhoc_pb_env[["t"]] <- Sys.time()
  37. .adhoc_pb_env[["n"]] <- 0
  38. } else
  39. {
  40. .adhoc_pb_env[["t"]] <- c(.adhoc_pb_env[["t"]],Sys.time())
  41. }
  42.  
  43. # update n and print line
  44. if(incremental) n <- .adhoc_pb_env[["n"]] + n
  45. .adhoc_pb_env[["n"]] <- n
  46. cat("r |",rep("+",n),rep(" ",100-n),"| ",n, "%",sep="")
  47.  
  48. # complete line, advise if requested, remove values and environment
  49. if(.adhoc_pb_env[["n"]] >= 100) {
  50. cat(" Task completed!n")
  51. if(advise){
  52. times <- cumsum(as.numeric(diff(.adhoc_pb_env[["t"]])))
  53. rec <- c(0,round(100 * times / tail(times,1)))
  54. cat("Recommended split:",rec,"(incremental:",c(0,diff(rec)),")n")
  55. }
  56. rm(list=ls(envir = .adhoc_pb_env),envir = .adhoc_pb_env)
  57. rm(.adhoc_pb_env,envir = globalenv())
  58. }
  59. }
  60.  
  61. {
  62. b(0);Sys.sleep(2)
  63. b();Sys.sleep(1)
  64. b();Sys.sleep(1)
  65. b(100,a=T)
  66. b(00);Sys.sleep(2)
  67. b(50);Sys.sleep(1)
  68. b(75);Sys.sleep(1)
  69. b(100)
  70. }
Add Comment
Please, Sign In to add comment