简体   繁体   English

R中选择function的总和

[英]summation of choose function in R

I am trying to create a function, that is identical to the pbinom in R, ie the density for a binomial distribution.我正在尝试创建一个 function,它与 R 中的 pbinom 相同,即二项分布的密度。

My code is the following:我的代码如下:

MyPBin <- function(X,n,p) {
  choose(n,X)*p^X*(1-p)^(n-X)
}

which should match the function used in pbinom in R: p(x) = choose(n, x) p^x (1-p)^(nx)这应该与 R 中 pbinom 中使用的 function 匹配: p(x) = choose(n, x) p^x (1-p)^(nx)

I am, however, not getting the correct result.但是,我没有得到正确的结果。 I think i have located the reason -- if i take the sum of all the individual choose functions (n=1, n=2, n=3 etc.) i get the same result as pbinom.我想我已经找到了原因——如果我将所有单独的选择函数(n=1、n=2、n=3 等)相加,我会得到与 pbinom 相同的结果。

So my question is : how can i sum all of the individual choose functions that the function uses, when i run it?所以我的问题是:当我运行 function 时,如何将所有单独的选择功能相加?

Use sum.使用总和。 These all give the same result.这些都给出了相同的结果。 (Note that MyPBin gives the same result as dbinom.) (请注意,MyPBin 给出的结果与 dbinom 相同。)

sum(MyPBin(0:3, 10, .3))
## [1] 0.6496107

sum(dbinom(0:3, 10, .3))
## [1] 0.6496107

pbinom(3, 10, .3)
## [1] 0.6496107

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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