# Any line that starts with a "#" is a called a "comment" and the computer ignores it
# This function takes in NO inputs, and returns either 1 or 2, each with 50% probability
# Normally your functions will do more than just one line
flip_coin = function(){
return(sample(2,1))
}
# This function takes in an input n, and simulates flipping a coin n times.
# The output is the number of heads (pretend 1 = heads, 2 = tails)
flip_n_coins = function(n){
# first we replicate the "flip_coin" function n times and store the result
many_flips = replicate(n, flip_coin())
# then we convert the result to a table, so instead of a list of 1s and 2s
# it just stores the # of 1s and the # of 2s
flip_table = table(many_flips)
# flip_table is a list of two things: the # of 1s (heads) and the # of 2s
# (tails). To get the k-th entry in a list L, we use L[[k]].
return(flip_table[[1]])
}
# The previous function represents one experiment: flip a coin 50 times, see how
# many heads come up. The next one is going to automatically repeat the experiment
# for us many times, and plot the results. It takes two inputs: num_coins is the number
# of flips per experiment, and num_repititions is the number of times to repeat the
# experiment.
flip_and_plot = function(num_coins, num_repetitions){
# first, we replicate the experiment [num_repetitions] times
all_experiments = replicate(num_repetitions, flip_n_coins(num_coins))
# you can try this in the console to see that all_experiments is now a list
# of length [num_repititions] in which each entry is a number saying how many
# heads came up in that run
# again, we want to convert to a table
all_experiments_table = table(all_experiments)
# now we plot it. There are many types of plots, and for each plot you can use many different
# input variables to change how it looks. Here, we won't use any of those.
barplot(all_experiments_table)
# we'll also return the result in addition to plotting the graph
return(all_experiments_table)
}
result_table = flip_and_plot(20, 10000)
print(result_table)