R:根据 newdata 上的 coxph 对象列表进行预测

R: Predictions from a list of coxph objects on newdata

我正在构建一系列 Cox 回归模型,并根据这些模型对新数据进行预测。在某些情况下,我能够获得预期的事件数量,但在其他情况下却不能。

比如coxph调用中的公式写出来,那么预测就计算出来了。但是,如果公式存储在一个对象中并且调用了该对象,则会出现错误。如果我尝试在 dplyr 管道变异函数中创建它们,我也无法获得预测(对于我正在编写的函数,这将是使预测正常工作的最理想位置)。

非常感谢任何帮助!

谢谢,

丹尼尔

require(survival)
require(tidyverse)
n = 15

# creating tibble of tibbles.
results = 
  tibble(id = 1:n) %>%
  group_by(id) %>%
  do(
    # creating tibble to evaluate model on
    tbl0 = tibble(time = runif(n), x = runif(n)),
    # creating tibble to build model on
    tbl =  tibble(time = runif(n), x = runif(n))
  ) %>%
  ungroup 

#it works when the formula is added the the coxph function already written out
  map2(results$tbl, results$tbl0, ~ predict(coxph( Surv(time) ~ x, data = .x), newdata = .y, type = "expected"))

#but if the formula is previously defined, I get an error
  f = as.formula(Surv(time) ~ x)
  map2(results$tbl, results$tbl0, ~ predict(coxph( f, data = .x), newdata = .y, type = "expected"))

# I also get an error when I try to include in a dplyr pipe with mutate
  results %>%
    mutate(
     pred = map2(tbl, tbl0, ~ predict(coxph( f, data = .x), newdata = .y, type = "expected"))
    )

我弄明白了(在朋友的帮助下)。如果您将公式定义为字符串,并在函数调用中将其强制转换为公式,一切都会顺利进行。我不确定它为什么有效,但它确实有效!

#define the formula as a string, and call it in the function with as.formula(.)
  f = "Surv(time) ~ x"
  map2(results$tbl, results$tbl0, ~ predict(coxph( as.formula(f), data = .x), newdata = .y, type = "expected"))

#also works in a dplyr pipe with mutate
  results %>%
    mutate(
     pred = map2(tbl, tbl0, ~ predict(coxph( as.formula(f), data = .x), newdata = .y, type = "expected"))
    )