1

My task is to recreate the result of this for loop by using the map() function. Unfortunately, I can't get my head around this.

play_roulette <- function(bet, number) {
  draw <- sample(0:36, 1)
  tibble(
    winning_number = draw,
    your_number = number,
    your_bet = bet,
    your_return = if (number == draw) {
      bet * 36
    } else {
      0
    }
  )
}


desired_length <- 10 
list_w_for <- vector(mode = "list", length = desired_length)

for(i in seq_along(list_w_for)){
  list_w_for[[i]] <- play_roulette(bet = 1, number = 5)
}


for_tibble <- bind_rows(list_w_for)
for_tibble

My current map code:

num_vec <- 1:10
bet_vec <- 1
tibble_2c <- tibble(x= bet_vec, y= num_vec)

map_dfc( tibble_2c,
    play_roulette(bet = x, number = y))
1
  • 1
    replicate(10, play_roulette(1, 5)) may be helpful. If everything is constant, then play_roulette2 = function (bet, number, sims){draws = sample(0:36, sims, TRUE); tibble(draws, number, bet, return = (number == bet) * bet)} Commented Jan 31, 2021 at 0:20

1 Answer 1

1

You just have to call the function 10 times, since the iterator i is not used inside of the function.

# use *_dfr to row_bind the result
map_dfr(
   # call the function ten times
   1:10, 
   # note that .x, the default iterator in map, is not needed inside of the function
   ~play_roulette(bet = 1, number = 5))  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.