R: Text progress bar in for loop
for progress bar to work you need a number to track your progress. that is one of the reasons as a general rule I prefer using for with (i in 1:length(ind))
instead of directly putting the object I want there. Alternatively you'll just create another stepi
variable that you do stepi = stepi + 1
in every iteration.
you first need to create the progressbar object outside the loop
pb = txtProgressBar(min = 0, max = length(ind), initial = 0)
then inside you need to update with every iteration
setTxtProgressBar(pb,stepi)
or
setTxtProgressBar(pb,i)
Remember to close the progress bar to output the newline character. From the documentation:
The progress bar should be closed when finished with: this outputs the
final newline character.
Simply add at the end of your loop:
close(pb)
This will work poorly if the loop also has print
commands in it
Progress bar on while loop in r studio
Can do like this
x <- rep(x = NA, times = 100)
pb <- txtProgressBar(0, length(x), style = 3)
for(i in 1:length(x)) {
setTxtProgressBar(pb, i)
x[i]
Sys.sleep(time = 1)
}
close(pb)
R More detailed progress bars in for loops
Self taught answer for getting the bar to fill. Example with loop that reads files:
df <- data.frame(x=(list.files("new/")))
total = length(df$x)
pb <- winProgressBar(title = "Progress Bar", label="0% done", min = 0, max =total , width = 300, initial=0)
for(i in df$x){
u <- fread(paste0("Z:/sec/new/",i))
setWinProgressBar(pb, which(df$x== i),label=paste( round(which(df$x== i)/total*100, 0),"% done"))
}
close(pb)
The time and scanning file sizes first I've yet to figure out.
Dynamic status message from inside a for loop
If it is OK to clear the console each time, you can:
for (i in 1:1000) {
for(j in 1:1000){
for(k in 1:1000){
cat(paste('\014',i, j, k))
}
}
}
Progress bar in R shiny for loop
I'm not sure if you can adapt the load bar of fileInput to respond to a loop, but here's an alternative with a new progress bar.
ui <- fluidPage(
# With this tag you can change the position and the size of the progress bar
# Without it, the bar will be at the bottom right corner of the screen
tags$head(tags$style(".shiny-notification {position: fixed;
opacity: 1 ;
top: 35% ;
left: 40% ;
height: 50px;
width: 300px}")),
titlePanel("Upload Files"),
sidebarLayout(
sidebarPanel(
fileInput("upload", "Select Files",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain"))
),
mainPanel(
tableOutput("table")
)
)
)
server <- function(input, output) {
observeEvent(input$upload, {
# wrap the loop execution in withProgress
withProgress(
message='Please wait',
detail='Doing important stuff...',
value=0, {
for (i in 1:5) { # changed the loop for demonstration purposes
Sys.sleep(0.8) # pretending to execute code
incProgress(amount=1/5)
}
})
})
output$table <- renderTable(print(input$upload$name))
}
shinyApp(ui,server)
Status Bar in for loop
The issue is that setTxtProgressBar
needs its value to be in the sequence min=0
to max=n
, as set in your txtProgressBar
. Since i
is really one of the unique values within mu_ut$AnimalID
, even if it is an integer, it is not clear that it is also in the range 0:n
.
Try this.
ids <- unique(mu_ut$AnimalID)
pb <- txtProgressBar(min = 0, max = length(ids), style = 3)
for (ind in seq_along(ids)) {
id <- ids[ind]
AnID <- paste("AnID", id, sep = ".")
assign(AnID, mu_ut[mu_ut$AnimalID == id,])
dbWriteTable(conn = db, name = AnID, value = mu_ut[mu_ut$AnimalID == id,],
field.types = c(DateAndTime = "DATETIME",
AnimalID = "CHAR",
Species = "CHAR",
Sex = "CHAR",
CurrentCohort = "CHAR",
BirthYear = "DATE",
CaptureUnit = "CHAR",
CaptureSubunit = "CHAR",
CaptureArea = "CHAR"), overwrite = TRUE)
Sys.sleep(1)
setTxtProgressBar(pb, ind)
}
(This is very similar to @CareyCaginalp's comment.)
Add a progress bar to a function
There is a package pbapply
, which provides a progress bar for apply-functions using:
pblapply(X, FUN, ..., cl = NULL)
It works just like a normal apply
-function.
This function: pblapply(1:10, function(x) {Sys.sleep(02); print(x)})
gave this output:
| | 0 % ~calculating [1] 1
|+++++ | 10% ~18s [1] 2
|++++++++++ | 20% ~16s [1] 3
|+++++++++++++++ | 30% ~14s [1] 4
|++++++++++++++++++++ | 40% ~12s [1] 5
|+++++++++++++++++++++++++ | 50% ~10s [1] 6
|++++++++++++++++++++++++++++++ | 60% ~08s [1] 7
|+++++++++++++++++++++++++++++++++++ | 70% ~06s [1] 8
|++++++++++++++++++++++++++++++++++++++++ | 80% ~04s [1] 9
|+++++++++++++++++++++++++++++++++++++++++++++ | 90% ~02s [1] 10
|++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed = 20s
Pretty neat. I don't know if it helps, but worth taking a look.
Related Topics
Automatic Documentation of Datasets
Replacing Nas in R with Nearest Value
How to Clean Twitter Data in R
How to Change the Na Color from Gray to White in a Ggplot Choropleth Map
Wrap Long Text in Kable Table Column
How to Create Datatable with Complex Header in R Shiny
Date Time Conversion and Extract Only Time
How to Show the Progress of Code in Parallel Computation in R
Adding Text to Ggplot Geom_Jitter Points That Match a Condition
Fast Replacing Values in Dataframe in R
How to Remove Duplicated Column Names in R
Rolling Window Over Irregular Time Series
Initialize an Empty Tibble with Column Names and 0 Rows
Differencebetween a List and a Pairlist in R
R: Robust Se's and Model Diagnostics in Stargazer Table