本文介绍了在R中循环以获取从零开始的组合总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下等式,我必须用R来写.

I have the following equation and I have to write it in R.

这种编码所面临的主要挑战是,对于每个i和每个k,我需要一个组合之和(分子中的二项式项).在这里,对于某些i和k,min {(n-k),Mi}可以为0,特别是当k = n时.最重要的是,循环不能从0开始,但是我需要它!

The main challenge that I am facing with this coding is that for each i and for each k, I need a sum of combinations (binomial terms in the numerator). Here min{(n-k),Mi} can be 0 for some i and k, specially when k=n. Most importantly a loop cannot be started from 0, but I need it!

出于您的考虑,以下是我的代码和数据(d1).您将看到我需要从sum<-0行之后的0开始循环,这是我的主要问题.您能看到问题并更正代码吗?应该从0开始的循环该怎么办?

For your kind consideration, here is my code and the data (d1). You will see that I need to start the loop from 0 after the line sum<-0, which is my main problem. Would you please see the issue and correct the code? What should I do with the loop that needs to be started from 0?

n<-4

n^2

id<-1:16

r<-c(1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1)

tr<-rep(0,n^2)
for(i in 1:n^2){
tr[i]<-ifelse(r[i]==1,rexp(1,1/1),0)
}

t0<-rep(0,n^2)
for(i in 1:n^2){
t0[i]<-ifelse(r[i]==0,rexp(1,1/1.5),0)
}

#Total number of subjects who cannot get B1:

M<-sum(r==0)    #If there were cenoring then M<-sum(r==0 & tr>cenc)

d<-data.frame(id,r,t0,tr)

d1<-d[tr>0,]
d1

d1<-d1[order(d1$tr),]
d1

d1$rank<-1:length(d1$tr)
d1


###Calculating the probability of getting B1 for each subject with r[i]=1:

d1$prob<-rep(0,length(d1$tr))
for(i in 1:length(d1$tr)){  #loop i begins
Mi<-sum(d1$tr[i]>t0[t0>0])
for(k in 1:n){  #loop k begins
sum<-0
for(m in 0:min(n-k,Mi)){    #loop m begins
sum<-sum+choose(Mi,m)*choose(n^2-i-Mi,n-k-m)
}   #loop m ends.
d1$prob[i]<-d1$prob[i]+choose(i-1,k-1)*sum/choose(n^2,n)
}   #loop k ends.
}   #loop i ends.
d1$prob<-d1$prob*1/n

推荐答案

我看不到原始代码中的问题是什么?您不能索引从零开始的向量,但它与循环中迭代器的范围无关.无论如何,这应该给您相同的答案,但避免了最内层的循环:

I don't see what is the problem in your original code? You can't index vectors beginning from zero, but it has nothing to do with the range of iterator in loops. Anyway, this should give you same answer but avoids the innermost loop:

d1$prob<-rep(0,length(d1$tr))
for(i in 1:length(d1$tr)){  #loop i begins
  Mi<-sum(d1$tr[i]>t0[t0>0])
  for(k in 1:n){  #loop k begins
    # function choose is vectorized, so you can compute all 
    # binomial terms at once given k
    SUM<-sum(choose(Mi,0:min(n-k,Mi))*choose(n^2-i-Mi,n-k-(0:min(n-k,Mi))))
    d1$prob[i]<-d1$prob[i]+choose(i-1,k-1)*SUM
  }   #loop k ends.
}   #loop i ends.
d1$prob<-(d1$prob/choose(n^2,n))*1/n 
#as choose(n^2,n) does not depend on i nor k, 
#you can make the division after the loops for all elements at once

这篇关于在R中循环以获取从零开始的组合总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 11:33