将函数与 R 中的向量参数集成 [英] Integrate function with vector argument in R

查看:38
本文介绍了将函数与 R 中的向量参数集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对之前的帖子有类似的挑战:如何将向量传递给整合功能

I have a similar challenge to a previous post: How to pass vector to integrate function

我有一个函数,我想对曲线下的面积进行积分.

I have a function which I want to integrate the area under the curve.

一、[生存]功能:

surv <- function(x,score) exp(-0.0405*exp(score)*x) # probability of survival

score 来自风险计算器,它调整生存估计.患者有不同的分数,例如:

score is from a risk calculator and it adjusts the survival estimate. Patients have different scores so, for example:

score <- c(0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1) # 7 different scores

计算所有 7 位患者的 surv 很容易,如果我们有一个特定的时间点 x:

Calculating the surv for all 7 patients is easy, if we have a specific time point x in mind:

surv(5, score) # Survival to year 5
[1] 0.7161497 0.6914399 0.6651219 0.6371998 0.6077026 0.5766890 0.5442516

但要获得种群的平均存活率或个体的预期存活率,我需要计算曲线下的面积,其中曲线由函数 surv 给出.我需要计算x=0x=Inf 限制下的面积.我需要为所有 7 个(在本例中)患者执行此操作.

But to get the mean survival of a population or the expected survival of an individual, I need to calculate the area under the curve, where the curve is given by the function surv. I need to calculate the area under the limits of x=0 and x=Inf. And I need to do this for all 7 (in this example) patients.

我引用的另一篇 stackoverflow 帖子也有类似的问题.目前尚不清楚该解决方案是否可以帮助我.我在下面介绍:

The other stackoverflow post I referenced has a similar problem. It's not clear that the solution can help me. I present it below:

integrate(Vectorize(fun_integrate,vectorize.args='x'), upper = 3, lower = -3, vec = rnorm(100),subdivisions=10000)

fun_integrate 是要集成的函数

vectorize.args 是要向量化并传递给 fun_integrate 的参数

vectorize.args is the arguments to be vectorized and passed to fun_integrate

vec 是作为要传递到 fun_integrate 的参数的值的向量

vec is the vector of values that served as the argument to be passed into the fun_integrate

我不知道什么是细分,但我认为这并不重要.

I have no idea what subdivisions is but I assume it's not important.

我尝试使用以下方法执行此操作:

I try to execute this with the following:

integrate(Vectorize(surv, vectorize.args="score"), lower=0, upper=Inf, score=score)
Error in integrate(Vectorize(surv, vectorize.args = "score"), lower = 0,  : 
  evaluation of function gave a result of wrong length

我尝试了不同的修改,但似乎没有任何结果.

I have tried different modifications and nothing seems to give a result.

您有什么建议吗?

推荐答案

您的操作顺序错误.您需要创建一个函数来计算给定分数的积分,并将其向量化.

You're doing it in the wrong order. You need to create a function that calculates the integral, for a given score, and vectorize that.

surv <- function(x,score) exp(-0.0405*exp(score)*x) # probability of survival
area <- function(score) integrate(surv,lower=0,upper=Inf,score=score)$value
v.area <- Vectorize(area)

scores <- c(0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1)  # 7 different scores
v.area(scores)
# [1] 14.976066 13.550905 12.261366 11.094542 10.038757  9.083443  8.219039

这篇关于将函数与 R 中的向量参数集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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