简体   繁体   中英

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.

You are using dbinom with a range of x values and then summing. Instead using pbinom , which calculates then probability of P(x <=q) (or P(x >q) if lower.tail = FALSE ).

Thus you can calculate P(x >6) + P(q <= 1) (which is what you appear to want to calculate)

pbinom(q = 6, p = p ,size = n, lower.tail = FALSE) + pbinom(q = 1, p = p, size = n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM