【问题标题】:R: how to repeatedly "loop" the results from a function?R:如何重复“循环”函数的结果?
【发布时间】:2020-12-02 05:54:27
【问题描述】:

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

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

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

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

我在下面发布了我的代码:

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

#here is my question:

#get results for some time (time >1001)
prediction <- ranger_preds$'1001' > 0.5     # time has to be in "unique.death.times."
real <- cost_test$time >= 1001

#get confusion matrix and sensitivity for this same time
confusion = confusionMatrix(as.factor(prediction), as.factor(real), positive = 'TRUE')
sensitivity_1001 = confusion$byclass[1]

#now, get the results for a second time
prediction <- ranger_preds$'2005' > 0.5     # for any time in unique.death.times.  "2005" 
real <- cost_test$time >= 2005

#get confusion matirx and sensitivity for the second time
confusion = confusionMatrix(as.factor(prediction), as.factor(real), positive = 'TRUE')
sensitivity_2005 = confusion$byclass[1]

#question: how do I get the "sensitivity" for all the times in "unique.death.times", the average sensitivity and "plot sensitivity vs unique death times"?

有人可以帮我吗?

谢谢

编辑:用户“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.

【问题讨论】:

    标签: r function loops for-loop repeat


    【解决方案1】:

    假设ranger_preds 的每个列名都采用数字形式,您可能会有类似的内容:

    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]
    }
    

    我们的想法是为sensitivity 创建一个列表,而不是创建多个变量,并将属性设置为names(range_preds) 中对应的time,即对于2005 年,我们将通过调用sensitivity$2005 来获得敏感度。

    我还没有对此进行测试,因此可能会出现错误并且它可能不是最有效的 - 但是,希望它会引导您朝着正确的方向前进。

    【讨论】:

    • 您好贾斯汀,感谢您的回复。您提供的代码似乎有效,但是前几个时间点的“混淆矩阵”没有 2 个因素,因此会给出错误:“confusionMatrix.default(as.factor(prediction), as.factor( real), : 数据必须包含一些与参考重叠的级别。”。你知道如何解决这个问题吗?谢谢
    • 我用您提供的答案发布了一个新问题:stackoverflow.com/questions/65118371/… 感谢您的所有帮助!
    猜你喜欢
    • 2012-11-03
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    相关资源
    最近更新 更多