如何解决如何在R函数之间传递参数?
我有2个小功能(DoAnalysis()
和ProcessRes()
)和1个最终功能(PerformSim()
),它们将调用这2个小功能。下面列出了详细的示例函数。
每个函数都包含一个唯一的参数(不重叠的参数):
- 函数
PerformSim()
包含1个唯一参数nsim
; - 函数
DoAnalysis()
包含1个唯一参数obj
; - 函数
ProcessRes()
包含1个唯一参数results
对于其余的参数,函数DoAnalysis()
具有完整的集合,函数DoAnalysis()
包含函数DoAnalysis()
的参数的子集,因此,函数PerformSim()
需要包含调用两个函数DoAnalysis()
和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,cutoff = 26){
## this is the simulation
total <- nS1 + nS2 + nS3
SimuTypeI <- map(1:nsim,~rbinom(total,0.4))
results <- map(SimuTypeI,~DoAnalysis(.x))
ProcessRes(results = results)
}
PerformSim(nsim = 1000)
解决方法
所有函数定义和参数看起来都不错,但是在PerformSim()
函数定义中,您必须在cutoff
中传递参数ProcessRes()
。这样。
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,cutoff)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。