# NOT RUN {
# 1) A simple progress indicator in percent
for (i in 0:101) {
progress(i)
Sys.sleep(0.01)
if (i == 101) message("Done!")
}
# 2) A progress indicator with 'x on y'
for (i in 0:31) {
progress(i, 30)
Sys.sleep(0.02)
if (i == 31) message("Done!")
}
# 3) A progress bar in percent
for (i in 0:101) {
progress(i, progress.bar = TRUE)
Sys.sleep(0.01)
if (i == 101) message("Done!")
}
# 4) A progress indicator with 'x on y'
for (i in 0:21) {
progress(i, 20, progress.bar = TRUE)
Sys.sleep(0.03)
if (i == 21) message("Done!")
}
# 5) A progression dialog box with Tcl/Tk
# }
# NOT RUN {
if (require(tcltk)) {
gui_progress <- function(value, max.value) {
# Do we need to destroy the progression dialog box?
if (value > max.value) {
try(tkdestroy(get_temp("gui_progress_window")), silent = TRUE)
delete_temp(c("gui_progress_state", "gui_progress_window",
"gui_progress_cancel"))
return(invisible(FALSE))
} else if (exists_temp("gui_progress_window") &&
!inherits(try(tkwm.deiconify(tt <- get_temp("gui_progress_window")),
silent = TRUE), "try-error")) {
# The progression dialog box exists
# Focus on it and change progress value
tkfocus(tt)
state <- get_temp("gui_progress_state")
tclvalue(state) <- value
} else {
# The progression dialog box must be (re)created
# First, make sure there is no remaining "gui_progress_cancel"
delete_temp("gui_progress_cancel")
# Create a Tcl variable to hold current progression state
state <- tclVar(value)
assign_temp("gui_progress_state", state)
# Create the progression dialog box
tt <- tktoplevel()
assign_temp("gui_progress_window", tt)
tktitle(tt) <- "Waiting..."
sc <- tkscale(tt, orient = "h", state = "disabled", to = max.value,
label = "Progress:", length = 200, variable = state)
tkpack(sc)
but <- tkbutton(tt, text = "Cancel", command = function() {
# Set a flag telling to stop running calculation
assign_temp("gui_progress_cancel", TRUE) # Content is not important!
tkdestroy(tt)
})
tkpack(but)
}
invisible(TRUE)
}
# Register it as function to use in progress()
change_temp(".progress", "gui_progress", gui_progress,
replace.existing = TRUE)
rm(gui_progress) # Don't need this any more
# Test it...
for (i in 0:101) {
progress(i) # Could also set console = FALSE for using the GUI only
Sys.sleep(0.05)
# The code to stop long calc when user presses "Cancel"
if (exists_temp("gui_progress_cancel")) {
progress(101, console = FALSE) # Make sure to clean up everything
break
}
if (i == 101) message("Done!")
}
# Unregister the GUI for progress
change_temp(".progress", "gui_progress", NULL)
}
# }
Run the code above in your browser using DataLab