View source: R/utilities_math.R

getRandomWalk | R Documentation |

Generates a random walk with flexible control over its range, trend, and smoothness. It works by calling stats::rnorm at each step and taking a cumulative sum of the generated values. Smoothness is controlled by initially generating a shorter random walk and upsampling.

getRandomWalk( len, rw_range = 1, rw_smoothing = 0.2, method = c("linear", "spline")[2], trend = 0 )

`len` |
an integer specifying the required length of random walk. If len is 1, returns a single draw from a gamma distribution with mean=1 and sd=rw_range |

`rw_range` |
the upper bound of the generated random walk (the lower bound is set to 0) |

`rw_smoothing` |
specifies the amount of smoothing, basically the number of points used to construct the rw as a proportion of len, from 0 (no smoothing) to 1 (maximum smoothing to a straight line) |

`method` |
specifies the method of smoothing: either linear interpolation ('linear', see stats::approx) or cubic splines ('spline', see stats::spline) |

`trend` |
mean of generated normal distribution (vectors are also acceptable, as long as their length is an integer multiple of len). If positive, the random walk has an overall upwards trend (good values are between 0 and 0.5 or -0.5). Trend = c(1,-1) gives a roughly bell-shaped rw with an upward and a downward curve. Larger absolute values of trend produce less and less random behavior |

Returns a numeric vector of length len and range from 0 to rw_range.

plot(getRandomWalk(len = 1000, rw_range = 5, rw_smoothing = 0)) plot(getRandomWalk(len = 1000, rw_range = 5, rw_smoothing = .2)) plot(getRandomWalk(len = 1000, rw_range = 5, rw_smoothing = .95)) plot(getRandomWalk(len = 1000, rw_range = 5, rw_smoothing = .99)) plot(getRandomWalk(len = 1000, rw_range = 5, rw_smoothing = 1)) plot(getRandomWalk(len = 1000, rw_range = 15, rw_smoothing = .2, trend = c(.1, -.1))) plot(getRandomWalk(len = 1000, rw_range = 15, rw_smoothing = .2, trend = c(15, -1)))

Embedding an R snippet on your website

Add the following code to your website.

For more information on customizing the embed code, read Embedding Snippets.