Search code examples
sqlrprogress-barrsqlite

Status Bar in for loop


I was trying to create a status bar in my for loop, but the status remains at 0%. I'm not sure what the issue could be.

  n <- length(unique(mu_ut$AnimalID))
  pb <- txtProgressBar(min = 0, max = n, style = 3)
  for(i in unique(mu_ut$AnimalID)){ 
     AnID <- paste("AnID", i, sep = ".")
     assign(AnID, mu_ut[mu_ut$AnimalID == i,])
     dbWriteTable(conn = db, name = AnID, value = mu_ut[mu_ut$AnimalID == i,], 
                  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, i)
  }

Is it a problem with the "i" argument in the setTxtProgressBar function?

Thank you in advance.


Solution

  • 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.)