Function of function always returns 0-R

Viewed 189

I am having a problem writing a function of a function in r. Specifically, I want to calculate the odds of a dice roll in Yahtzee, and when I use explicit parameters, I get a numeric value:

large_straight <- function(){
  rolls <- sample(6, size = 5, replace = TRUE)
  if(all(Numbers %in% c(rolls))) {
    1
  } else if (all(Numbers2 %in% c(rolls))) {
    1
  } else 0
}

sum(replicate(1000, large_straight()))/1000

returns a non-zero value,

but when I try to generalize, so that I can pass not just large straights but also other dice rolls:

my_roll_odds <- function(Size, FUN){
  sum(replicate(Size, FUN))/Size
}

my_roll_odds(1000, large_straight())

I always get a return value of 0, and I have zero idea why. Any help would be greatly appreciated!

1 Answers

I think the function could not be evaluated correctly because of the nested calls. Here is a way with match.fun

my_roll_odds <- function(Size, FUN){
    sum(replicate(Size, match.fun(FUN)()))/Size
}

my_roll_odds(1000, large_straight)
#[1] 0.029

my_roll_odds(1000, large_straight)
#[1] 0.037
Related