I have the following function, 'n' rolls of 'k' dice, in which the result is the sum of 'k' rolls.
rolldie = function(n, k){
# Your code here
die=sample(1:6, size = k, replace = TRUE)
replicate(n, sum(sample(c(1:6),k, replace=TRUE)))
}
rolldie(5, 4)
I then have to create a ggplot histogram to show the results of the function, using n=1000 with whatever values of k. That is where I am stuck, I am not sure how to create this histogram for the results of rolldie.
CodePudding user response:
ggplot expects a data frame, so you could try this ...
library(ggplot2)
data.frame(die_sums = rolldie(1000, 10))|>
ggplot()
geom_histogram(aes(die_sums), binwidth = 1)
Created on 2022-02-13 by the reprex package (v2.0.1)
CodePudding user response:
Here is a solution with a simplified rolldie
function.
Roll the dies, table the results, coerce the table to data.frame
and plot.
library(ggplot2)
rolldie <- function(n, k){
replicate(n, sum(sample(6, k, replace=TRUE)))
}
set.seed(2022)
n <- 1000
Points <- rolldie(n, 4)
Points <- as.data.frame(table(Points))
ggplot(Points, aes(Points, Freq))
geom_col()
Created on 2022-02-13 by the reprex package (v2.0.1)
CodePudding user response:
Here is one solution:
library(janitor)
data <- tabyl(rolldie(1000, 1)) %>% rename(Number = 1)
ggplot(data = data, aes(x= as.factor(Number), y=n, label = Number))
geom_col()
geom_text(aes(label = n), vjust = -0.5)