-
Notifications
You must be signed in to change notification settings - Fork 1
/
ScriptOne.r
73 lines (53 loc) · 1.58 KB
/
ScriptOne.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
############### THIS IS MY FIRST SCRIPT USING R STUDIO, GIT AND GITHUB
## first executable command - the random walk, which is what this currently feels like
#compiling function
rand.walk<-function(sim.number,sim.length){
#creating initital objects
n0<-rnorm(1)
n.vec<-rep(NA,sim.length)
#simulation loop
for(j in 1:sim.number){
#random walk loop
for(i in 1:sim.length){
if(i==1){n.old<-n0}
if(i>1){n.old<-n.vec[i-1]}
n.vec[i]<-n.old+rnorm(1)
} # end random walk loop - now collect the data
if(j == 1){n.sims<-n.vec}
if(j > 1){n.sims<-cbind(n.sims,n.vec)}
}
n.sims.df<-as.data.frame(n.sims)
names(n.sims.df)<-seq(1:sim.number)
#doing summary statistics of the simulations
summary.df<-as.data.frame(t(
apply(
as.data.frame(n.sims), 1, function(x) c(mean(x),sd(x))
)
))
names(summary.df)<-c("mean","sd")
summary.df[,"n.plus.sd"]<-summary.df[,1]+summary.df[,2]
summary.df[,"n.minus.sd"]<-summary.df[,1]-summary.df[,2]
# initiating printing of plot of summary results
plot(summary.df[,"mean"],
type = "l",
ylim = c(min(summary.df),max(summary.df)),
xlab = "time",
ylab = "n"
)
#plotting standard deviation
polygon(x = c(1:sim.length, sim.length:1),
y = c(summary.df[,"n.minus.sd"], rev(summary.df[,"n.plus.sd"])),
col = "grey70"
)
#plotting mean
lines(summary.df[,1])
## creating a list to return objects
return.object<-list()
return.object[["summary"]]<-summary.df
return.object[["sims"]]<-n.sims.df
## returning objects
return(return.object)
}
#setting parameters
set.seed(234)
output<-rand.walk(sim.number=500,sim.length=200)