3

I am using a for loop obtain a set of p-values using the "pbinom" function. The values 1:5 simply refer to the number of observed counts, 21, refers to the sample size, and 0.05 refers to the probability of success:

for ( i in 1:5) {
print (1 - pbinom(i, 21, 0.05))
}

[1] 0.2830282
[1] 0.08491751
[1] 0.01888063
[1] 0.00324032
[1] 0.0004415266

This code works fine, but it just outputs the values the values on the command prompt as above.

My question is, how can I store the output in a variable?

I tried

output<-for ( i in 1:5) {
print (1 - pbinom(i, 21, 0.05))
}

But when I entered "output", I received "NULL" in response.

Any help would be appreciated, Thanks.

2 Answers 2

4

Don't use a for loop at all for this. pbinom is vectorized. Just do

(output <- 1 - pbinom(1:5, 21, 0.05))
## [1] 0.2830281552 0.0849175139 0.0188806334 0.0032403196 0.0004415266

In a worst case scenario you can use sapply instead which outputs the vector by default, something like

(output <- 1 - sapply(1:5, pbinom, 21, 0.05))
## [1] 0.2830281552 0.0849175139 0.0188806334 0.0032403196 0.0004415266
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your answer, David. I just have one follow up question: If had multiple probabilities of success, say 0.05 and 0.02. How can I get the same output in your answer, but with a vector of p-values for each success probability (separated by row), such that row one represents the pvalues for 0.05 and row two represents the pvalues from 0.02?
1 - pbinom(1:2, 21, c(0.02, 0.05))?
I tried this, but only outputs the pvalues for the first value in the vector, so all pvalues for 0.02
Nope. Compare to 1 - pbinom(1:2, 21, 0.05) and 1 - pbinom(1:2, 21, 0.02) and then find the difference.
So after entering all the above commands, I see that 1 - pbinom(1:2, 21, c(0.02, 0.05)), I get [1] 0.06534884 0.08491751, which corresponds to the outputs obtained by: 1 - pbinom(1, 21, 0.02) and 1 - pbinom(2, 21, 0.05), respectively. My desired output would be: [1] 0.065348840 0.008125299 (row 1) and [1] 0.28302816 0.08491751 (row 2). Perhaps you got this output? I'm not sure what I'm doing incorrectly. Thanks again.
|
1

You can't pass a for loop into a variable like that. You could try this:

output=c()
for (i in 1:5){
output[i]=(1-pbinom(i,21,0.05))
}

Then if you type:

output

R will produce:

[1] 0.2830281552 0.0849175139 0.0188806334 0.0032403196 0.0004415266

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.