Wednesday, 21 August 2013

Using Parameter Vectors of Different Lengths in R

Using Parameter Vectors of Different Lengths in R

Assume I have two different parameter vectors used as inputs in a
function. Also, assume the two parameter vectors are of different lengths.
Is there a way to output all the possible values of that function? I know
that if I use two parameter vectors of different lengths, then the shorter
parameter vector is just repeated so that doesn't work. I can solve this
"manually" as you can see below. But, I'd like to find a more efficient
manner of calculating all the possible combinations. An example follows:
Assume I'm using the dbinom() function that has as inputs x (number of
"successes" from the sample), n (number of observations in the sample),
and p (the probability of "success" for each x). n stays constant at 20;
however, my x varies from 7,8,9,...,20 ("x7" below) or 0,1 ("x1" below).
Also, I want to evaluate dbinom() at different values of p, specifically
from 0 to 1 in .1 increments ("p" below). As you can see the three
parameter vectors x7, x1, and p are all of different lengths 14, 2, and
11, respectively.
> p<-seq(from=0,to=1,by=.1)
> x7<-seq.int(7,20)
> x1<-c(0,1)
> n<-20
I can evaluate each combination by using one of the vectors (x7/x2 or p)
in dbinom() and then selecting a value for the remaining parameter. As you
can see below, I used the vector x7 or x2 and then "manually" changed the
p to equal 0,.1,.2,...,1.
> sum(dbinom(x7,n,.1))
[1] 0.002386089
> sum(dbinom(x7,n,.1))+sum(dbinom(x1,n,.1))
[1] 0.3941331
> sum(dbinom(x7,n,.2))+sum(dbinom(x1,n,.2))
[1] 0.1558678
> sum(dbinom(x7,n,.3))+sum(dbinom(x1,n,.3))
[1] 0.3996274
> sum(dbinom(x7,n,.4))+sum(dbinom(x1,n,.4))
[1] 0.7505134
> sum(dbinom(x7,n,.5))+sum(dbinom(x1,n,.5))
[1] 0.9423609
> sum(dbinom(x7,n,.6))+sum(dbinom(x1,n,.6))
[1] 0.9935345
> sum(dbinom(x7,n,.7))+sum(dbinom(x1,n,.7))
[1] 0.999739
> sum(dbinom(x7,n,.8))+sum(dbinom(x1,n,.8))
[1] 0.9999982
> sum(dbinom(x7,n,.9))+sum(dbinom(x1,n,.9))
[1] 1
> sum(dbinom(x7,n,1))+sum(dbinom(x1,n,1))
[1] 1
Basically, I want to know if there is a way to get R to print all the sums
above from 0.3941331,0.1558678,...,1 with a single line of input or some
other more efficient way of varying the parameter p without simply copying
and changing p on each line.
*I'm new to Stackoverflow, so I apologize in advance if I have not
formulated my question conventionally.

No comments:

Post a Comment