首页 > 解决方案 > 如何在R中通过递归扩展项目

问题描述

我想使用递归方式扩展矩阵。后面的列由前面的列决定。矩阵的维度也发生了变化。这是一个例子:


#the sample size in each clinical-stage, for example in stage 1, we will recruit 8 patients; in stage 2 
# we will recruit another 9 patients
nsample <- c(8,9,7)

#the threshold for each stage which means the number of patients with positive results should be large #than threshold. it shows in accumulation way. For example, in stage 1, more than 2 patients should be #positive which means least 3 patients should be positive, then stage 2 trial will be conducted. At stage #2, at least 6 patients, which is the threshold 5 plus 1, should be positive in 17,which is the number of #patients in the first two stages, patients, then stage 3 trial will be #conducted.

threshold <- c(2,5,10)

y_want1 <- c((threshold[1]+1):nsample[1])
y_want2 <- c()
for(i in 1:length(y_want1)){
  y_want2_lowboundary <- threshold[2] - y_want1[i] + 1
  if(y_want2_lowboundary>0){
  stage2 <- expand.grid(y_want1[i],y_want2_lowboundary:nsample[2])
  
  y_want2 <- rbind(stage2,y_want2)
  }
  else{
    stage2 <- expand.grid(y_want1[i],1:nsample[2])
    y_want2 <- rbind(stage2,y_want2)
  }
}

y_want3 <- c()
for(i in 1:dim(y_want2)[1]){
  y_want3_lowboundary <- threshold[3] - sum(y_want2[i,]) + 1
  if(y_want3_lowboundary >0){
  stage3 <- expand.grid(y_want2[i,1],y_want2[i,2],y_want3_lowboundary:nsample[3])
  y_want3 <- rbind(stage3,y_want3)
  }
  else{
    stage3 <- expand.grid(y_want2[i,1],y_want2[i,2],1:nsample[3])
    y_want3 <- rbind(stage3,y_want3)
  }
}

finalresult <-y_want3

问题是阶段的数量是不同的。例如,下一次,将计算 Nsample 的长度为 5 或 6 个阶段。我们无法预先确定它。如何编写一个将 Nsample 和阈值作为参数传递的函数来生成最终结果?

标签: r

解决方案


推荐阅读