Lin
Lin

Reputation: 97

Create a accumulated binomial distribution table

I am new to R and trying to build a accumulative binomial distribution table and got stuck in the loop.

r = readline("please enter an interger n:")

p = seq(from = 0.1, to = 1,by = 0.1 )
r = seq(from = 0, to = 100)

n <- ""
for (each in r) {

 x=qbinom(x,r,p)
}
print(x)

This is an sample table I want to get

Upvotes: 2

Views: 601

Answers (1)

user20650
user20650

Reputation: 25914

As an alternate to the loop: you can use expand.grid to create all permutations of k and p, and further avoid the loop as pbinom can take vectors.

# Create input values
p = 1:9/10
k = 0:25
n = 25

# Create permutations of `k` and `p`: use this to make grid of values
ex <- expand.grid(p=p, k=k)

# Find probabilities for each value set
ex$P <- with(ex, pbinom(k, n, p ))

# Reshape to your required table format
round(reshape2::dcast(k ~ p, data=ex, value.var = "P"), 3)

Loop approach

# Values to match new example
p = 1:19/20
k = 0:25
n = 4

# Create matrix to match the dimensions of our required output
# We will fill this as we iterate through the loop
mat1 <- mat2 <- matrix(0, ncol=length(p), nrow=length(k), dimnames=list(k, p))

# Loop through the values of k
# We will also use the fact that you can pass vectors to `pbinom`
# so for each value of `k`, we pass the vector of `p`
# So we will update each row of our output matrix with 
# each iteration of the loop

for(i in seq_along(k)){

     mat1[i, ] <- pbinom(k[i], n, p)

}

Just for completeness, we could of updated the columns of our output matrix instead - that is for each value of p pass the vector k

for(j in seq_along(p)){

  mat2[, j] <- pbinom(k, n, p[j])

}

# Check that they give the same result
all.equal(mat1, mat2)

Upvotes: 2

Related Questions