Rish
Rish

Reputation: 826

store for loop values in variable in R

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.

Upvotes: 3

Views: 4832

Answers (2)

David Arenburg
David Arenburg

Reputation: 92300

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

Upvotes: 4

jimh
jimh

Reputation: 1946

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

Upvotes: 1

Related Questions