R:来自newdata上的coxph对象列表的预测

时间:2017-11-15 15:09:41

标签: r dplyr prediction purrr

我正在构建一系列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"))
    )

1 个答案:

答案 0 :(得分:0)

我想出来了(在朋友的帮助下)。如果将公式定义为字符串,并且在函数调用中将其强制转换为公式,则一切都会顺利运行。我不确定它为什么会起作用,但确实如此!

#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"))
    )