【发布时间】:2020-10-26 03:00:30
【问题描述】:
我有 2 个小函数(DoAnalysis() 和 ProcessRes())和 1 个最终函数(PerformSim()),它们将调用 2 个小函数。下面列出了详细的示例函数。
每个函数都包含一个唯一的参数(非重叠参数):
- 函数
PerformSim()包含1 个唯一参数nsim; - 函数
DoAnalysis()包含1 个唯一参数obj; - 函数
ProcessRes()包含 1 个唯一参数results
对于剩余的参数,函数DoAnalysis()有完整的集合,函数DoAnalysis()包含函数DoAnalysis()的参数子集,因此,函数PerformSim()需要包含调用这两个函数@的信息987654334@和ProcessRes()。
以下代码不起作用,因为我不确定如何在函数之间正确传递参数。
请帮助并提前非常感谢您的帮助。
library(purrr)
DoAnalysis <- function(obj, nS1 = 40, nS2 = 40, nS3 = 20, cutoff) {
cumS2 <- nS1 + nS2 ## this is the total number of patients at the end of Stage 2
nmax <- cumS2 + nS3 ## this is the total number of patients at the end of study
## compute number of events for 1st stage
Res_n <- sum(obj[1:nS1]) ## this is the number of response in Stage 1
## compute number of events for 2nd stage
Res_n2 <- sum(obj[1:cumS2]) ## this is the number of response in Stage 2
### Now, it is the final analysis
Res_F <- sum(obj[1:nmax]) ## this is the number of response in Final
list(Res_n, Res_n2, Res_F)
}
ProcessRes <- function(results, cutoff){
part1 <- part2 <- part3 <- c()
for (i in 1:length(results)){
part1 <- as.vector(c(part1, results[[i]][[1]]))
part2 <- as.vector(c(part2, results[[i]][[2]]))
}
resultsTypeI <- as.data.frame(cbind(part1, part2, part3))
names(resultsTypeI) <- c("Res_n", "Res_n2")
resultsTypeI$fulFlag <- ifelse(resultsTypeI$Res_n2 < cutoff, 1, 0)
R_1 <- mean(resultsTypeI$fulFlag)
return(c(R_1))
}
set.seed(20201022)
PerformSim <- function(nsim, nS1 = 40, nS2 = 40, nS3 = 20, cutoff = 26){
## this is the simulation
total <- nS1 + nS2 + nS3
SimuTypeI <- map(1:nsim, ~rbinom(total, 1, 0.4))
results <- map(SimuTypeI, ~DoAnalysis(.x))
ProcessRes(results = results)
}
PerformSim(nsim = 1000)
【问题讨论】:
-
变量
R_2,R_3,R_4,R_5定义在哪里? -
您可以使用 do.call 并将参数作为列表传递给每个函数。
-
@Shan,感谢您指出。该代码是根据现有代码修改的,忘记更改这部分。现在,它在问题中更新为仅保留 R_1。
-
@Econ_matrix 你能提供更多细节吗?我不确定如何通过传递参数来处理这行代码,因为它调用函数 DoAnalysis results