传递两个或多个向量来整合函数

Pass two or more vectors to integrate function

我试图整合这个函数,其中 k1 和 m1 是两个输入向量

k_z <- function(z, k1, m1) {
  k_z <- k1 * exp(-z / m1)
}

我改编了this question

的解决方案
integrate(Vectorize(k_z, vectorize.args = "z"), upper = 2, lower = 0, k1 = rnorm(10), m1 = rnorm(10))

但出现以下错误

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

我尝试了很多不同的方法都无济于事。我做错了什么?谢谢!

您的函数 k_z 不是标量点“函数”,因为它不会 return 给定一组值的单个值集成函数所需的参数(因为它是一对多的):让 k_z return 像下面这样的单个值,它将起作用:

k_z <- function(z, k1, m1) {
  sum(k1 * exp(-z / m1)) # return a single value, not a vector of multiple values
}

k_z_vec <- Vectorize(k_z, vectorize.args = "z")
integrate(k_z_vec, upper = 2, lower = 0, k1 = rnorm(10), m1 = rnorm(10))
# -7.338221e+14 with absolute error < 1.4e+07

如果您想计算具有不同值的多个积分 向量 k1 和 m1,您可以尝试以下操作:

k_z <- function(z, k1, m1) {
  k1 * exp(-z / m1)
}
k1 <- rnorm(10)
m1 <- rnorm(10)
sapply(1:10, function(x) integrate(k_z, upper = 3, lower = -3, k1=k1[x], m1=m1[x]))

            [,1]         [,2]         [,3]         [,4]         [,5]       [,6]         [,7]         [,8]         [,9]         [,10]       
value        -21.4522     4.330284e+40 19.4474      3.900487e+21 9649111978 2.092415e+57 -34.86148    10103.57     -8.232609    46.35694    
abs.error    2.381672e-13 2.705507e+35 2.159095e-13 1.129735e+17 83251.15   1.180714e+49 3.870402e-13 0.0003484398 9.140032e-14 5.942846e-10
subdivisions 1            4            1            3            2          5            1            1            1            1           
message      "OK"         "OK"         "OK"         "OK"         "OK"       "OK"         "OK"         "OK"         "OK"         "OK"        
call         Expression   Expression   Expression   Expression   Expression Expression   Expression   Expression   Expression   Expression