Created
September 11, 2016 17:11
-
-
Save Kornel/341c28b15f67f8ebd73fd6dd1d706699 to your computer and use it in GitHub Desktop.
Random walk in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
walk <- function(N, p = 0.5) { | |
cumsum((-1)^rbinom(N, 1, 1 - p)) | |
} | |
# Convergence of the random walk | |
l <- sapply(1:1000, function(n){ | |
N <- 100 | |
tail(walk(N, 0.5), 1) | |
}) | |
plot(density(l)) | |
x <- seq(min(l), max(l), len = 100) | |
hx <- dnorm(x, mean(l), sd(l)) | |
lines(x, hx, col = 'red') | |
# Display 3 random walks | |
N <- 1000 | |
a <- walk(N, p = 0.5) | |
b <- walk(N, p = 0.45) | |
c <- walk(N, p = 0.40) | |
df <- data.frame(x = rep(1:N, 3), y = c(a, b, c), idx = rep(c('a', 'b', 'c'), each = N)) | |
ggplot(df) + | |
geom_line(aes(x = x, y = y, colour = idx)) + | |
scale_color_brewer(palette = 'Dark2') + | |
theme_bw() |
Author
Kornel
commented
Sep 11, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment