Ryan Kmet
Ryan Kmet

Reputation: 65

Function of function always returns 0-R

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!

Upvotes: 6

Views: 344

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

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

Upvotes: 1

Related Questions