如何创建循环(当级别不与参考重叠时)

How to Create a loop (when levels do not overlap the reference)

我在 R 中编写了一些代码。此代码获取一些数据并将其拆分为训练集和测试集。然后,我在训练集上拟合了一个“生存随机森林”模型。之后,我使用该模型预测测试集中的观察结果。

由于我正在处理的问题类型(“生存分析”),必须为每个“唯一时间”(在文件“unique.death.time”内)制作一个混淆矩阵。对于为每个唯一时间制作的每个混淆矩阵,我感兴趣的是相应的“灵敏度”值(例如 sensitivity_1001、sensitivity_2005 等)。我正在尝试获取所有这些灵敏度值:我想用它们绘制一个图(与独特的死亡时间相比)并确定平均灵敏度值。

为了做到这一点,我需要在“unique.death.times”中重复计算每个时间点的灵敏度。我尝试手动执行此操作,但需要很长时间。

有人可以告诉我如何用“循环”来做到这一点吗?

我已经 post 编辑了下面的代码:

#load libraries
library(survival)
library(data.table)
library(pec)
library(ranger)
library(caret)

#load data
data(cost)

#split data into train and test
ind <- sample(1:nrow(cost),round(nrow(cost) * 0.7,0))
cost_train <- cost[ind,]
cost_test <- cost[-ind,]

#fit survival random forest model
ranger_fit <- ranger(Surv(time, status) ~ .,
                data = cost_train,
                mtry = 3,
                verbose = TRUE,
                write.forest=TRUE,
                num.trees= 1000,
                importance = 'permutation')

#optional: plot training results
plot(ranger_fit$unique.death.times, ranger_fit$survival[1,], type = 'l', col = 'red')    # for first observation
lines(ranger_fit$unique.death.times, ranger_fit$survival[21,], type = 'l', col = 'blue')  # for twenty first observation

#predict observations test set using the survival random forest model
ranger_preds <- predict(ranger_fit, cost_test, type = 'response')$survival
ranger_preds <- data.table(ranger_preds)
colnames(ranger_preds) <- as.character(ranger_fit$unique.death.times)

之前 post (R: how to repeatedly "loop" the results from a function?) 的另一位用户 (Justin Singh) 从这里建议了如何创建循环:

sensitivity <- list()
for (time in names(ranger_preds)) {
    prediction <- ranger_preds[which(names(ranger_preds) == time)] > 0.5
    real <- cost_test$time >= as.numeric(time)
    confusion <- confusionMatrix(as.factor(prediction), as.factor(real), positive = 'TRUE')
    sensitivity[as.character(i)] <- confusion$byclass[1]
}

但是由于在这个循环中使用了一些观察结果,我得到了以下错误:

Error in confusionMatrix.default(as.factor(prediction), as.factor(real),  : 
  The data must contain some levels that overlap the reference.

有谁知道如何解决这个问题? 谢谢

prediction and/or real 中的某些值只有 1 个唯一值。确保因素的水平相同。

sapply(names(ranger_preds), function(x) {
  prediction <- factor(ranger_preds[[x]] > 0.5, levels = c(TRUE, FALSE)) 
  real <- factor(cost_test$time >= as.numeric(x), levels = c(TRUE, FALSE))
  confusion <- caret::confusionMatrix(prediction, real, positive = 'TRUE')
  confusion$byClass[1]
}, USE.NAMES = FALSE) -> result

result