The code below generates what appears almost as an animation in R studio because it renders 100 plots, each plot has slightly more data than then previous plot.
################################################################################
# Visualise probability of heads tending towards 0.5 as more tests performed
# Number of tests to run
tests <- 100
# duration to run for in seconds
durationSeconds <- 10
ht <- sample(c('heads', 'tails'), tests, replace=TRUE)
total <- vector()
for (i in 1:tests) {
headsAtI <- length(which(ht[1:i] == 'heads'))
total[i] <- headsAtI/i
Sys.sleep(durationSeconds/tests)
plot(total, type='l')
abline(h = 0.5, col='blue')
}
This works but has some serious issues:
- 100 plots are created, I guess ideally one should be created and re-used
- If I change the value of 'tests' to be say 10,000, R Studio will hang or crash
What is the proper way to do this in R Studio?
I realise that I can just draw a single plot at the end, with all the "results", but I want to achieve the "animation" effect.