Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make execution pause, sleep, wait for X seconds in R?

How do you pause an R script for a specified number of seconds or miliseconds? In many languages, there is a sleep function, but ?sleep references a data set. And ?pause and ?wait don't exist.

The intended purpose is for self-timed animations. The desired solution works without asking for user input.

like image 226
Dan Goldstein Avatar asked Oct 15 '22 01:10

Dan Goldstein


People also ask

How do I pause an execution in R?

If we want to force the R programming language to make a pause, we can use the Sys. sleep function. The following R code is exactly the same as before, but this time we are adding a break of 5 seconds to every run of the for-loop by using the Sys.

How do you sleep in R?

1 Answer. You can use the Sys. sleep function from the base package to suspend execution for a given time interval.

What is pause function in Javascript?

pause function returns a Promise when called. The Promise itself resolves after a specified amount of time, giving us the ability to chain some piece of code and delay it. Sort of a flow control mechanism for code execution.


2 Answers

See help(Sys.sleep).

For example, from ?Sys.sleep

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)

Yielding

> testit(3.7)
   user  system elapsed 
  0.000   0.000   3.704 
like image 177
Dirk Eddelbuettel Avatar answered Oct 16 '22 14:10

Dirk Eddelbuettel


Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
{
  print(i)
  date_time<-Sys.time()
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}
like image 17
rbtj Avatar answered Oct 16 '22 14:10

rbtj