【问题标题】:How to run a bunch of models in R using a Function如何使用函数在 R 中运行一堆模型
【发布时间】:2020-05-15 22:27:06
【问题描述】:
library(survival)
justices <- read.csv("http://data.princeton.edu/pop509/justices2.csv")
PREDS = c("age", "year")
m = coxph(Surv(tenure, event == 1) ~ age + year, data = justices)
summary(m)

exp(coef(m)[1])
exp(confint(m,level=(1-0.05/1))[1,])


DVMOD <- function(PREDS, data){
  t <- coxph(paste0("Surv(tenure, event == 1) ~ "), PREDS + number + name, data = data)
  return((c(PREDS, coef(t)[1], confint(t)[1,])))
}

all_models <- lapply(PREDS,DVMOD, PREDS = PREDS, data=justices)

我希望为 PREDS 中的每个变量运行单独的 coxph 模型,然后存储该变量的名称及其风险比和置信带。

【问题讨论】:

  • PREDS 在哪里定义为 DVMOD 函数之外的变量列表?
  • @Len Greski 我更新了对不起!
  • 你研究过 tidymodels 吗?我知道这是运行一堆模型的整洁方法。

标签: r lapply sapply mapply survival


【解决方案1】:

如果您使用as.formula() 转换公式字符串,您可以更改DVMOD() 函数中的自变量,如下所示:

DVMOD <- function(PREDS, data){
     theFormula <- paste("Surv(tenure, event == 1) ~ ",PREDS," + number + name")
     t <- coxph(as.formula(theFormula), data = data)
     return((c(PREDS, coef(t)[1], confint(t)[1,])))
}
DVMOD("age",justices)
all_models <- lapply(c("age"),function(x,y){
     DVMOD(x,y)
},justices)

由于year 的模型不收敛(即直接使用year 作为year 的值调用DVMOD() 时失败),具有2 个变量的lapply() 失败,但它适用于@ 987654329@。

...和输出:

> all_models
[[1]]
                                    age               2.5 %              97.5 % 
              "age"  "24.4400841925434" "-20.8849057264629"  "69.7650741115497" 

> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    相关资源
    最近更新 更多