如何在R中找到概率 [英] How to find probability in R
问题描述
如何在 R 中的 sample
命令中使用 prob
参数,以便它也涵盖条件概率?例如字母表中的字母:生成字母b"的概率取决于前一个生成的字母.
How could you use the prob
argument in the sample
command in R so that it covers conditional probability as well? For example, the letters of the alphabet: the probability of generating the letter 'b' depends on the previous letter generated.
谢谢!
推荐答案
这个问题还是有点难回答,如果你指定一个条件概率的例子会有帮助,另见 此处.
The question is still a bit difficult to answer, it would help if you specified an example of the conditional probability, seealso here.
但是如果我们假设我们有a、b和c,并且a和b很可能出现在彼此之后,我们可以继续从这里,和我们可以修改函数如下:
But if we assume that we have a,b, and c, and a and b have a high probability of occuring after eachother, we can continue on the answer from here, and we could modify the function as follows:
# n = number of elements
# sample_from = draw random numbers from this range
random_non_consecutive <- function(n=10,sample_from = seq(1,5))
{
y= rep(NA, n)
prev=-1 # change this if -1 is in your range, to e.g. max(sample_from)+1
probs = rep(1,length(sample_from));names(probs)=sample_from
for(i in seq(n)){
# your conditional probability rules should go here.
if(prev=="a")
{
probs = c('a'=0,'b'=0.9,'c'=0.1)
}
if(prev=="b")
{
probs = c('a'=0.9,'b'=0,'c'=0.1)
}
if(prev=="c")
{
probs = c('a'=0.9,'b'=0.1 ,'c'=0)
}
y[i]=sample(setdiff(sample_from,prev),1,prob = probs[names(probs) %in% setdiff(sample_from,prev)])
prev = y[i]
}
return(y)
}
在这种情况下,a 和 b 出现的概率很高.事实上:
In this case, a and b have a high probability of occuring after eachother. And indeed:
random_non_consecutive(40,letters[1:3])
[1] "c" "a" "b" "a" "b" "a" "b" "c" "b" "a" "b" "a" "b" "a" "b" "a" "b" "a" "b" "a" "b" "a" "b" "a" "c" "a" "b" "a" "b" "c" "a" "b" "a" "b" "a" "b" "a" "b" "a" "c"
希望这会有所帮助.
这篇关于如何在R中找到概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!