I tried to make R roll a D20 and say a prompted text line with specific random variables between 1 and 20.
d20roll <- sample(1:20,1,replace=FALSE);d20roll
ifelse(d20roll>18 & d20roll<21,'Summon a dragon')
ifelse(d20roll>12 & d20roll<18,'Cast haste on the nearest archer')
ifelse(d20roll<12,'Go directly to jail, do not pass go','reroll')
2
Here is a solution with findInterval
.
cut_points <- c(0, 12, 18, 21, Inf)
action <- c(
'Go directly to jail, do not pass go',
'Cast haste on the nearest archer',
'Summon a dragon',
'reroll'
)
set.seed(2024)
d20roll <- sample(20L, 1L); d20roll
#> [1] 2
i <- findInterval(d20roll, cut_points)
action[i]
#> [1] "Go directly to jail, do not pass go"
Created on 2024-09-08 with reprex v2.1.0
Note that findInterval
is vectorized so if you want to run it R
times, just change the call to sample
to sampling with replacement.
R <- 100L
d20roll <- sample(20L, R, replace = TRUE)
i <- findInterval(d20roll, cut_points)
action[i] |> table()
#>
#> Cast haste on the nearest archer Go directly to jail, do not pass go
#> 35 50
#> Summon a dragon
#> 15
Created on 2024-09-08 with reprex v2.1.0