R语言Shiny应用中如何动态传递参数至cohort()函数?
解决方案
首先替换原代码中用assign生成变量的方式,改用列表存储所有条件(这种方式更安全,也更适合Shiny环境,避免污染全局环境):
library(Capr) # 初始化列表存储筛选条件 attrition_conditions <- list() for (i in seq(2)) { # 生成条件并添加到列表,同时设置对应名称 attrition_conditions[[paste0('ad_cr', i)]] <- atLeast(1L, query = condition(cs(descendants(i)))) }
接下来,给列表中的每个条件套上withAll(),再通过do.call()动态构建attrition对象:
# 为每个条件包裹withAll attrition_args <- lapply(attrition_conditions, withAll) # 动态调用attrition函数,传入命名参数 attrition_obj <- do.call(attrition, attrition_args)
最后将构建好的attrition_obj传入cohort()函数即可:
cd <- cohort( entry = condition(cs(100)), attrition = attrition_obj, exit = exit(endStrategy = observationExit()) )
若需保留原assign方式(不推荐)
如果一定要用assign生成全局变量,可通过变量名列表构建参数:
# 获取所有生成的变量名 var_names <- paste0('ad_cr', seq(2)) # 从环境中取出变量并包裹withAll,构建命名参数列表 attrition_args <- lapply(var_names, function(name) { withAll(get(name)) }) names(attrition_args) <- var_names # 构建attrition对象并调用cohort attrition_obj <- do.call(attrition, attrition_args) cd <- cohort( entry = condition(cs(100)), attrition = attrition_obj, exit = exit(endStrategy = observationExit()) )
原理说明:attrition()接受多个命名参数,通过构建命名列表并配合do.call(),可以实现动态传递参数,效果完全等价于手动写出attrition('ad_cr1' = withAll(ad_cr1), 'ad_cr2' = withAll(ad_cr2))的形式。
内容的提问来源于stack exchange,提问作者sutsabs
相关产品推荐
相关产品推荐

