如何在map2()函数中指定predict.coxph的类型?附建模背景
Hey there! Let's work through how to specify the type parameter for predict.coxph within map2()—I’ve been in this exact situation before with nested survival models, so I know the confusion!
First, let’s recap your setup: you’ve got a nested data frame with your trained coxph models stored in one column, and presumably the datasets you want to predict on in another (let’s call these columns model and test_data for this example).
The key here is that map2() lets you pair each model with its corresponding dataset, and you just need to pass the type argument directly to predict.coxph inside the map2 call. Here’s a straightforward example:
library(tidyverse) library(survival) # Update your nested data frame to add predictions your_nested_df <- your_nested_df %>% mutate( # Replace "risk" with your desired type: "link", "expected", "terms" all work predictions = map2(model, test_data, ~ predict(.x, newdata = .y, type = "risk")) )
Let’s break this down:
.xrefers to each individualcoxphmodel from themodelcolumn.yrefers to the corresponding dataset from thetest_datacolumn- The
typeparameter accepts values like:"risk": Returns the relative risk score (most common for survival predictions)"link": Returns the linear predictor (log hazard)"expected": Returns the expected number of events"terms": Returns the contributions of each model term
If you want to bind the predictions directly to your test data (instead of storing them as a separate list column), you can adjust the code like this:
your_nested_df <- your_nested_df %>% mutate( predicted_data = map2(model, test_data, ~ .y %>% mutate(risk_score = predict(.x, newdata = ., type = "risk"))) )
A quick heads-up: Double-check that your test datasets have the exact same variable names and types as the training data you used to fit the coxph models—mismatches here will throw errors. Also, make sure there are no unexpected missing values in the test data that would break the prediction.
Hope this gets you sorted out! Let me know if you run into any edge cases or need further tweaks.
内容的提问来源于stack exchange,提问作者Wendy Tate

