Home > Mobile >  Creating a random number simulation in R
Creating a random number simulation in R

Time:09-28

I would like to create a random simulation in R where Person A can choose a whole number between 0:500, then I use sample() to randomly select a whole number between 0 and 500. The outcome of this model is to determine the square difference between the number Person A chose and the random number generated, or vice versa.

For example, if Person A chose 5 and the random number generator picked 25, then Person A has to pay me $(25 - 5)^2 = $400. If Person A choose 25 and the random number generator says 10, then Person A would pay me $(25 - 10)^2 = $225. Person A always has to pay unless he/she perfectly guessed my number.

possible.numbers <- 0:500
chosen.numbers <- 0:500

generated.number <- 
  sample(possible.numbers, 1, replace = TRUE)   

expected.payment <- (generated.number - 30)^2  #assuming I chose $30

print(expected.payment)

I don't think my codes are correct, any help will be greatly appreciated, thanks in advance!

CodePudding user response:

I'm not sure if you are saying you want to specify a chosen number or randomly sample a "chosen" number. At any rate, the function below should allow you to do both - just leave blank if you want to let the function "choose" the chosen number for you, or someone can specify the number to "choose."

set.seed(123)

example_function <- function(chosen = NULL, possible_numbers = 0:500){
  if(is.null(chosen)){
    chose <- sample(possible_numbers, 1)
  } else {
    chose <- chosen
  }
  random <- sample(possible_numbers, 1)
  payment <- (random - chose) ^ 2
  return(c(chosen = chose, random = random, payment = payment))
}

Outputs:

example_function()
# > example_function()
# chosen  random payment 
# 414     462    2304 

example_function(chosen = 2)
# > example_function(chosen = 2)
# chosen  random payment 
# 2     178   30976 
  • Related