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 milliseconds? 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.


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

According to R Documentation:

Using this function allows R to temporarily be given very low priority and hence not to interfere with more important foreground tasks. Typical use is to allow a process launched from R to set itself up and read its input files before R execution is resumed.

For example:

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)
 testit(3.7)
   user system elapsed
   0.00 0.00 3.71
testit(5)
   user system elapsed
   0.01 0.00 5.05
To know more about this function see help(Sys.sleep).
What is SYS sleep?
Sys.sleep(time) time – The number of seconds to pause R activity.

Your Answer

Interviews

Parent Categories