Biostats_R
Biostats_R

Reputation: 9

Coding a function

I have an assignment question that I feel would be easier with a function. I tried it and received an error. My question is, how could I code the highlighted math into a function? I want the function to return the probability output when I change the sample size.

In the highlighted math, for example, the sample size is 24 and I have to select 20.

Picture Below.

enter image description here

I want the function to essentially be like the equation below, and I want to input different sample sizes to produce the output.

P(X=20) &=& {Sample_Size \choose 20}* (0.90^20)*(0.10^4) = "Output"

Here is what I tried doing to no avail, with the error

unexpected symbol in "Probability<-function ..."

Probability <- function(Sample_Size) {Probability<- choose(Sample_Size,X)*.9^X *.10^(Sample_Size-X) return(Probability)

Upvotes: 1

Views: 74

Answers (2)

brinyprawn
brinyprawn

Reputation: 450

There is already a function in R that will do this for you. It is called dbinom (since it looks like you are working with the binomial distribution).

Here is an example of how to use it:

dbinom(x = 20, size = 24, prob = 0.9)
#> [1] 0.1291874
dbinom(x = 21, size = 24, prob = 0.9)
#> [1] 0.221464
dbinom(x = 22, size = 24, prob = 0.9)
#> [1] 0.2717968

Created on 2020-09-13 by the reprex package (v0.3.0)

  • The first parameter (x) takes the number of success you want to get the probability of.

  • The second (size) takes the sample size

  • And the third (prob) takes the probability of a success.

Upvotes: 1

D.J
D.J

Reputation: 1304

it should look like this:

your_input # sample_size

Probability<-function(Sample_Size, X) {
   Probability<- choose(Sample_Size,X)*.9^X *.10^(Sample_Size-X) 
   return(Probability)
 }
    
Probability(your_input, 20) # 20 being a random input number -> depends on your X value

see @Rui Barradas 's answer

Upvotes: 0

Related Questions