r - 如何在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 和阈值作为参数传递的函数来生成最终结果?
解决方案
推荐阅读
- java - 如何使用访问其他 bean 的 servlet 过滤器进行单元测试
- python - 是否有一种可移植的方式来提供在 PyPI 上分发的包的本地化?
- mysql - SQL 错误代码:1172 更新未插入
- java - 拆分字符串!在 JAVA 中
- spring - 在 Spring Boot 2.0.2 版本中注入特定数据源
- javascript - JS中数组的两个正确答案
- bash - 如何通过 SSH 使用 CURL 并获取文件以及返回值?
- vue.js - 使用 Vuex 设置 Vue.js
- angularjs - 当控制台日志给出好的结果时,如何显示与我的控制台日志相同的数据?
- c# - 使用 cookie 在 HttpWebRequest (WPF) 中自动设置国家