Home > Net >  in R: show the progress of a loop that is looping by a character and not a numeric variable
in R: show the progress of a loop that is looping by a character and not a numeric variable

Time:11-28

Is there a way to show the progress of a loop that is looping by a character and not a numeric variable?

I have example data and loop below. I am looping by glm formula from df2. This isn't the best example because all the formulas are the same but it should still work and will be able to show progress if there is a way to do so.

I am pretty sure the progress() function from svMisc package only works when looping a numeric variable?

#load packages 
library(tidyverse)
library(gamlj)

#add example data 
df1 <- read.csv("https://stats.idre.ucla.edu/stat/data/hdp.csv")
df1

#data with formulas for loop 
df2 <- structure(list(Column1 = c("remission ~ 1   IL6   CRP  (1   IL6   CRP | DID)", 
                                  "remission ~ 1   IL6   CRP  (1   IL6   CRP | DID)", "remission ~ 1   IL6   CRP  (1   IL6   CRP | DID)", 
                                  "remission ~ 1   IL6   CRP  (1   IL6   CRP | DID)", "remission ~ 1   IL6   CRP  (1   IL6   CRP | DID)", 
                                  "remission ~ 1   IL6   CRP  (1   IL6   CRP | DID)", "remission ~ 1   IL6   CRP  (1   IL6   CRP | DID)", 
                                  "remission ~ 1   IL6   CRP  (1   IL6   CRP | DID)", "remission ~ 1   IL6   CRP  (1   IL6   CRP | DID)", 
                                  "remission ~ 1   IL6   CRP  (1   IL6   CRP | DID)")), row.names = c(NA, 
                                                                                                     -10L), class = "data.frame")

# just need a character vector for the model formulas                                                                                          
fmlas <- unlist(df2)

model_list <- list()
for (xx in fmlas){
  model_list[[xx]] <- glm(as.formula(xx), data = df1)
}

CodePudding user response:

You can loop over the indices i of fmlas and do xx <- fmlas[i]:

n <- length(fmlas)
pbar <- txtProgressBar()
for(i in 1:n) {
  xx <- fmlas[i]
  model_list[[xx]] <- glm(as.formula(xx), data = df1)
  setTxtProgressBar(pbar, i/n)
}
close(pbar)
  • Related