在过去的几天里,我一直在浏览web,查看map2的文档。我已经获取了一个训练集,嵌套了数据并为其创建了coxph模型,并将这些模型保存在嵌套表中。现在我想从该模型进行预测,但根据文档,我想使用类型=–expected“as(
R documentation: predict.coxph
)
受试者的生存概率等于exp(-预期值)
我修改了相关代码,使用mpg数据集再现了我的问题。
我下面有4个例子,在预测函数确实起作用之后,它们不起作用。请注意,我已删除coxph。此集合中的模型为空,因此只有类(coxph)的模型。此代码可用于复制错误。
#Needed libraries
library(ggplot2)
library(tidyverse)
library(purrr)
library(broom)
library(survival)
#Create data set
mpg_data <- mpg
mpg_data <- mpg_data %>%
mutate(mpg_diff = cty - hwy)
mpg_data <- mpg_data %>%
mutate(EVENT = (mpg_diff >= -8))
set.seed(1)
mpg_data <- mpg_data %>%
mutate(TIME_TO_EVENT = as.integer(runif(234, 1, 100)))
mpg_nested <- mpg_data %>%
group_by(manufacturer) %>%
mutate(n_prot = length(model)) %>%
nest()
# Stepwise regression
stepwise <- function(data) {
response <- Surv(time = data$TIME_TO_EVENT, event = data$EVENT, type = "right")
full <- "Surv(time = data$TIME_TO_EVENT, event = data$EVENT, type = 'right') ~ data$cyl+data$cty+data$hwy+data$displ"
x <- factor(as.factor(data$model))
full <- ifelse(nlevels(x) >= 2, paste(full, "as.character(data$model)", sep = "+"), full)
x <- factor(as.factor(data$trans))
full <- ifelse(nlevels(x) >= 2, paste(full, "as.character(data$trans)", sep = "+"), full)
x <- factor(as.factor(data$drv))
full <- ifelse(nlevels(x) >= 2, paste(full, "as.character(data$drv)", sep = "+"), full)
null_model_ONE <- coxph(response ~ 1, data=data)
full_model_ONE <- coxph(as.formula(full), data=data)
model_ONE <- step(null_model_ONE, scope=list(lower=null_model_ONE, upper=full_model_ONE))
}
survival_mpg <- mpg_nested %>%
mutate(model_fit = map(data, stepwise))
#Predicting values
#This works but is not type="expected"
survival_mpg_predict <- survival_mpg %>%
mutate(mpg_predict = map2(model_fit, data, predict))
##TRY 1##
predict.F <- function(model_fit, data){
predict(model_fit, newdata=data, type="expected")
}
survival_mpg_predict <- survival_mpg %>%
mutate(mpg_predict = map2(model_fit, data, predict.F))
#Error in mutate_impl(.data, dots) : Evaluation error: requires numeric/complex matrix/vector arguments.
##Try 2##
survival_mpg_predict <- survival_mpg %>%
mutate(mpg_predict = map2(model_fit, data, predict(model_fit, newdata = data, type="expected")))
#Error in mutate_impl(.data, dots) : Evaluation error: no applicable method for 'predict' applied to an object of class "list".
##Try 3##
survival_mpg_predict <- survival_mpg %>%
mutate(mpg_predict = map2(model_fit, data, ~ predict(.x, newdata = .y, type="expected")))
#Error in mutate_impl(.data, dots) : Evaluation error: requires numeric/complex matrix/vector arguments.
##Try 4##
survival_mpg_predict <- survival_mpg %>%
mutate(mpg_predict = map2(model_fit, data, function(model_fit, data) predict(model_fit, newdata=data, type="expected")))
#Error in mutate_impl(.data, dots) : Evaluation error: requires numeric/complex matrix/vector arguments.