我对之前的帖子有类似的挑战:How to pass vector to integrate function
我有一个函数,我想对曲线下的面积进行积分。
首先是[生存]函数:
surv <- function(x,score) exp(-0.0405*exp(score)*x) # probability of survival
score
来自风险计算器,它调整了生存估计。患者有不同的分数,例如:
score <- c(0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1) # 7 different scores
计算所有 7 名患者的 surv
很容易,如果我们有一个特定的时间点 x
:
surv(5, score) # Survival to year 5
[1] 0.7161497 0.6914399 0.6651219 0.6371998 0.6077026 0.5766890 0.5442516
但要获得人口的平均存活率或个体的预期存活率,我需要计算曲线下的面积,其中曲线由函数 surv
给出。我需要计算 x=0
和 x=Inf
范围内的面积。我需要为所有 7 名(在本例中)患者执行此操作。
我引用的其他 stackoverflow 帖子也有类似的问题。目前尚不清楚该解决方案是否可以帮助我。我在下面介绍:
integrate(Vectorize(fun_integrate,vectorize.args='x'), upper = 3, lower = -3, vec = rnorm(100),subdivisions=10000)
fun_integrate
是要集成的函数
vectorize.args
是要矢量化并传递给 fun_integrate 的参数
vec
是作为参数传递给 fun_integrate 的值向量
我不知道什么是分割,但我认为它不重要。
我尝试使用以下命令执行此操作:
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
我尝试了不同的修改,但似乎没有任何结果。
你有什么建议吗?
最佳答案
你的顺序错了。您需要创建一个函数来计算给定分数的积分,并将其矢量化。
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 - 在 R 中将函数与矢量参数集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437585/