[英]Probability function in R
I am trying to write the function s_i = P(X+X+Y=i)
in R.我正在尝试在 R 中编写 function
s_i = P(X+X+Y=i)
。 I have the following distributions:我有以下分布:
I write this code我写这段代码
a_i <- function(k){
if (k == 0) return (3/4)
if (k == 1) return (1/8)
if (k == 2) return (1/8)
else return(0)
}
b_i <- function(k){
if (k == 0) return (1/10)
if (k == 1) return (8/10)
if (k == 2) return (1/10)
else return(0)
}
s_i<-function(i){
sas<-0
for (x1 in 0:2){
for(x2 in 0:2){
for(y in 0:2){
if(x1+x2+y==i){
sum=a_i(x1)*a_i(x2)*b_i(y)
sas=sas+sum
}
}
}
}
return(sas)
}
I am not sure if I understand correctly this function.我不确定我是否正确理解了这个 function。 Any ideas?
有任何想法吗?
First of all, your function is correct.首先,你的 function 是正确的。
Your Method你的方法
Applying your functions, you can see the distribution in the format of data.frame
like below应用你的函数,你可以看到
data.frame
格式的分布,如下所示
v <- 0:6
res1 <- data.frame(s = v, prob = sapply(0:6, s_i))
such that这样
> res1
s prob
1 0 0.0562500
2 1 0.4687500
3 2 0.2265625
4 3 0.1843750
5 4 0.0468750
6 5 0.0156250
7 6 0.0015625
Cross-Check交叉检查
In what follows, I generate the whole sample space to verify your obtained distribution接下来,我生成整个样本空间来验证您获得的分布
space <- setNames(expand.grid(replicate(3,0:2,simplify = F)),c("X1","X2","Y"))
space$s <- rowSums(space)
space <- within(space, prob <- Vectorize(a_i)(X1)*Vectorize(a_i)(X2)*Vectorize(b_i)(Y))
where you can see the whole space in data frame is您可以在哪里看到数据框中的整个空间
> space
X1 X2 Y s prob
1 0 0 0 0 0.0562500
2 1 0 0 1 0.0093750
3 2 0 0 2 0.0093750
4 0 1 0 1 0.0093750
5 1 1 0 2 0.0015625
6 2 1 0 3 0.0015625
7 0 2 0 2 0.0093750
8 1 2 0 3 0.0015625
9 2 2 0 4 0.0015625
10 0 0 1 1 0.4500000
11 1 0 1 2 0.0750000
12 2 0 1 3 0.0750000
13 0 1 1 2 0.0750000
14 1 1 1 3 0.0125000
15 2 1 1 4 0.0125000
16 0 2 1 3 0.0750000
17 1 2 1 4 0.0125000
18 2 2 1 5 0.0125000
19 0 0 2 2 0.0562500
20 1 0 2 3 0.0093750
21 2 0 2 4 0.0093750
22 0 1 2 3 0.0093750
23 1 1 2 4 0.0015625
24 2 1 2 5 0.0015625
25 0 2 2 4 0.0093750
26 1 2 2 5 0.0015625
27 2 2 2 6 0.0015625
then the distribution can be summarized as那么分布可以概括为
res2 <- aggregate(prob ~ s, space,sum)
such that这样
> res2
s prob
1 0 0.0562500
2 1 0.4687500
3 2 0.2265625
4 3 0.1843750
5 4 0.0468750
6 5 0.0156250
7 6 0.0015625
which is the same as res1
这与
res1
相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.