rbernoulli-probability

How to define a bernoulli density function?


The following is the funciton defined for bernoulli distribution. I am a new R user. I am not quite well-understand the following codes.

dbernoulli <- function(x, prob=0.5) {
dbinom(x, size=1, prob=prob)
 }

dbernoulli(y, prob=0.7)

I thought in the defined function, we have pre-determined the argument prob as 0.5 , so why can we change it to 0.7 when we use the defined function? Is these codes resonable? Can I correct it as follows?

dbernoulli <- function(x, prob) {
dbinom(x, size=1, prob=prob)
 }

dbernoulli(y, prob=0.7)

Solution

  • When you write function(x, prob=0.5) what you say is:

    create a function that receives two parameters,

    Hence, if you call the function dbernoulli(y) it will assign x = y and because you didn't pass a value for prob, it will assign prob = 0.5 because that's the default value you've defined for it.

    Now, if you remove the default value for prob, like function(x, prob), then you'll always be required to state the prob you want to use when calling the function, as in dbernoulli(y,prob = 0.7).