产生更有效的for循环 [英] Producing a more efficient for loop

查看:73
本文介绍了产生更有效的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个函数,该函数将Cox回归模型应用于测试数据,基于协变量创建生存函数,然后针对每个测试观察从当前时间开始预测生存概率.

I have created a function which applies a Cox regression model to test data, creates survival functions based on covariates, and then predicts the survival probability 30 days from current time for each test observation.

以下示例使用了肺部数据集,并且效果很好.但是,将数据应用于我自己的数据很繁琐.对于n = 60000,我一个小时后才停止使用它,因为对于打算使用该程序的目的而言这是不切实际的.

The example below uses the lung dataset and works quite well. However, applied to my own data the processing time is tedious. For n = 60000, I just stopped it after an hour as it is not practical for what I intend to use the program for.

看看代码结构,有什么明显的方法可以加快速度吗?

Looking at the code structure, is there an obvious way I can speed this up?

require(dplyr, survival, pec)

cox_model <- coxph(Surv(time, status) ~ sex, data = lung)

surv_preds <- function(model, query) {

  prediction <- vector(mode = "numeric", length = nrow(query))
  time <- 30

  for(i in 1:nrow(query)) {
    prediction[i] <- predictSurvProb(model, newdata = query[i, ], times = query[i, "time"] + time)
  }
  prediction
}

surv_preds(cox_model, lung)

推荐答案

已解决!如果有兴趣,我想发布我使用的解决方案.我设法完全消除了for循环的需要.

SOLVED!! In case it is of interest, I want to post the solution that I used. I managed to remove the need for the for loop entirely.

predictSurvProb(cox_model, 
                newdata = lung, 
                times = lung[ , "time"] + 30)[1, ]

这给了我所需的输出.关键是我从结果矩阵中索引第一行及其所有列.该代码为每个观察值使用唯一的生存函数估计量,以预测从观察值在曲线上的当前位置起30天的生存概率.

This gives me the output I require. The key is that I index the first row and all its columns from the resulting matrix. This code uses the unique survival function estimate for each observation to predict the survival probability 30 days from the observation's current position on the curve.

@thc给出的答案实际上最终指向正确的方向.

The answer from @thc actually pointed me in the right direction in the end.

这篇关于产生更有效的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆