【问题标题】:R: Predictions from a list of coxph objects on newdataR:来自新数据上的 coxph 对象列表的预测
【发布时间】:2017-11-15 15:09:40
【问题描述】:

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

例如,如果写出 coxph 调用中的公式,则会计算预测。但是,如果公式存储在一个对象中并且该对象被调用,我会得到一个错误。如果我尝试在 dplyr 管道 mutate 函数中创建它们,我也无法获得预测(对于我正在编写的函数,这将是让预测正常工作的最理想的地方)。

非常感谢任何帮助!

谢谢你,

丹尼尔

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

【问题讨论】:

    标签: r dplyr prediction purrr


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-03-08
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      相关资源
      最近更新 更多