Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

How to print progress bar of R function without for loop?

I have a function that takes a long time to run (involves many calculations in a large dataset). I want to include a progress bar to see if it's making progress. My function has no for loops; I don't understand how to add a progress bar if I don't have a for loop in the function.

I tried adding a for loop to get the progress bar to work, but it's just printing the progress bar without doing the calculations (I believe), i.e. when I print result I get NULL:

install.packages("svMisc")
require("svMisc")

# Test function
funct<-function(a,b,c)for (i in 0:101){
  progress(i, progress.bar=TRUE)
  Sys.sleep(0.01)
  x<-a*a
  y<-x+b
  z<-y/2
  if (i == 101) message("Done!")
}

result <- funct(-2.6e+70,-2.5e+121,6)
result

Feel free to suggest something other than svMisc.

question from:https://stackoverflow.com/questions/65598437/how-to-print-progress-bar-of-r-function-without-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In general, reporting the progress of a function will require a loop (or possibly a number of lines of code), as you've set out in your example. Your example is performing the calculations, it is just not returning them - remember that R functions return the value of the last calculation unless there is an explicit return() statement. In this case, the message() function returns NULL.

The minor modification to your code below demonstrates the expected behaviour of the progress bar, followed by result having the calculated value.

install.packages("svMisc")
require("svMisc")

# Test function
funct<-function(a,b,c){
  for (i in 0:101){
    progress(i, progress.bar=TRUE)
    Sys.sleep(0.01)
    x<-a*a
    y<-x+b
    z<-y/2
    if (i == 101) message("Done!")
  }
  return(z)
}

result <- funct(-2.6e+70,-2.5e+121,6)

#           0%---------25%---------50%---------75%--------100%
# Progress: ||||||||||||||||||||||||||||||||||||||||||||||||||
# Done!

result

# [1] 3.38e+140

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...