-
Notifications
You must be signed in to change notification settings - Fork 0
/
random_walks.R
97 lines (77 loc) · 2.75 KB
/
random_walks.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# ---- libraries ----
library(ggplot2)
library(tidyverse)
library(dplyr)
library(viridis)
# ---- function for several random walks ----
rw <- function(n = 1000, repetitions = 3){
if(repetitions == 0){
print("why do you want to plot 0 random walks?")
}
else{
repetitions <- round(repetitions)
if(repetitions < 0){
print("Please enter a positive integer")
}
else{
# this function creates a number of random walks of length n
tseries = NULL
# let's create a random serie
for(i in 1:repetitions){
x <- e <- rnorm(n)
# generate random walks
for(t in 2:n){
x[t] <- x[t - 1] + e[t]
}
x <- as.data.frame(x)
tseries <- bind_cols(tseries, x)
}
# name the series
colnames(tseries) <- sprintf("S%s", seq(1:repetitions))
# create a time variable
tseries$t <- 1:n
# create the plot background
if(repetitions > 1){
p <- p <- ggplot(data = tseries,
aes(x = t)) +
theme_classic() +
theme(
panel.grid.major.y = element_line(color = "black",
linetype = "dotted",
size = 0.1),
panel.grid.minor.y = element_line(color = "black",
linetype = "dotted"),
plot.title = element_text(hjust = 0.5)
) +
xlab("Time") +
ylab("Value at time t") +
labs(title = paste(as.character(repetitions),
"random walks generated"))
}
else{
p <- p <- ggplot(data = tseries,
aes(x = t)) +
theme_classic() +
theme(
panel.grid.major.y = element_line(color = "black",
linetype = "dotted",
size = 0.1),
panel.grid.minor.y = element_line(color = "black",
linetype = "dotted"),
plot.title = element_text(hjust = 0.5)
) +
xlab("Time") +
ylab("Value at time t") +
labs(title = paste(as.character(repetitions),
"random walk generated"))
}
# add the layers of each random walk
for(i in names(tseries)[-length(tseries)]){
p <- p + geom_line(aes_string(y = i,
color = shQuote(rgb(viridis.map[runif(1,1,nrow(viridis.map)),1:3]))),
show.legend = F)
}
return(p)
}
}
}