0

I am working on a script that should estimate the probability of having at least 2 out of n people having a same birthday within k days from eachother. To estimate this I have the following function:

birthdayRangeCheck.prob = function(nPeople, seperation, nSimulations) {
count = 0
for (i in 1:nSimulations) {
   count = count + birthdayRangeCheck(nPeople, seperation)
}
return(count / nSimulations)
}

Now just entering simple values for nPeople, seperation, nSimulations gives me a normal number. e.g.

birthdayRangeCheck.prob(10,4,100)
-> 0.75

However when I want to plot the probability as a function of nPeople, and seperation I stumble upon the following problem:

x = 1:999
y = 0:998
z = outer(X = x, Y = y, FUN = birthdayRangeCheck.prob, nSimulations = 100)

numerical expression has 576 elements: only the first used... (a lot of times)

So it seems like outer is not entering single elements of x and y, but rather the vectors themselfs, which is the opposite of what outer should do right?

Am I overlooking something? Because I can't figure out what is causing this error. (replacing FUN with e.g. sin(x+y) works like a charm so I did pin it down to the function itself. But since the function works just fine with numeric arguments I don't see why R doesn't understand to just enter elements of x and y as arguments.)

Any help would be greatly appreciated. Thanks ;)

Caseus
  • 1
  • Your `birthdayRangeCheck.prob` function is not vectorized. If you pass in a vector of values, it needs to return a vector of values. For example `birthdayRangeCheck.prob(1:2, 0:1)` only returns one number (well, presumably because you did not include `birthdayRangeCheck` so I can't actually run the code). Here's an existing question about vectorizing a function: https://stackoverflow.com/questions/50766836/r-vectorization-of-a-user-defined-function – MrFlick Feb 27 '20 at 16:09
  • Right so the function `outer` is not seperately entering combinations of x and y? Because that's what I thought it did. That's why I didn't understand why this didn't work. – Caseus Feb 27 '20 at 16:14
  • Outer only takes care of "crossing" the X and Y values. It calls your function once with the resulting input. Thus your function needs to be vectorized. It does not repeatedly call your function with different input. – MrFlick Feb 27 '20 at 16:17

0 Answers0