R 如何将向量传递给积分函数

R 如何将向量传递给积分函数,r,R,我想集成一个函数fun\u integrate,该函数有一个向量vec作为输入参数: fun_integrate <- function(x, vec) { y <- sum(x > vec) dnorm(x) + y } #Works like a charm fun_integrate(0, rnorm(100)) integrate(fun_integrate, upper = 3, lower = -3, vec = rnorm(100)) 300.997

我想集成一个函数
fun\u integrate
,该函数有一个向量
vec
作为输入参数:

fun_integrate <- function(x, vec) { 
  y <- sum(x > vec)
  dnorm(x) + y
}

#Works like a charm
fun_integrate(0, rnorm(100))

integrate(fun_integrate, upper = 3, lower = -3, vec = rnorm(100))
300.9973 with absolute error < 9.3e-07
Warning message:
  In x > vec :
  longer object length is not a multiple of shorter object length
fun\u集成向量机:
较长的对象长度不是较短对象长度的倍数
就我所见,问题如下:
integrate
调用
fun\u integrate
来计算
x
的向量,该向量是基于
upper
lower
计算的。此矢量化调用似乎不适用于作为附加参数传递的另一个矢量。我想要的是,
integrate
为它内部计算的每个
x
调用
fun\u integrate
,并将单个
x
与向量
vec
进行比较,我很确定我上面的代码不会这样做

我知道我可以自己实现一个集成例程,即计算
lower
upper
之间的节点,并分别评估每个节点上的函数。但这不是我喜欢的解决方案

还要注意,我选中了
Vectorize
,但这似乎适用于另一个问题,即函数不接受
x
的向量。我的问题是我需要一个额外的向量作为参数。

integrate(Vectorize(fun\u integrate,Vectorize.args='x'),上=3,下=-3,vec=rnorm(100),细分=10000)
integrate(Vectorize(fun_integrate,vectorize.args='x'), upper = 3, lower = -3, vec = rnorm(100),subdivisions=10000)

304.2768 with absolute error < 0.013


#testing with an easier function
test<-function(x,y) {
  sum(x-y)
}

test(1,c(0,0))
[1] 2

test(1:5,c(0,0))
[1] 15
Warning message:
In x - y : 
longer object length is not a multiple of shorter object length

Vectorize(test,vectorize.args='x')(1:5,c(0,0))
[1]  2  4  6  8 10

#with y=c(0,0) this is f(x)=2x and the integral easy to solve
integrate(Vectorize(test,vectorize.args='x'),1,2,y=c(0,0))
3 with absolute error < 3.3e-14 #which is correct
304.2768,绝对误差<0.013 #使用更简单的功能进行测试
测试罗兰的答案看起来不错。只是想指出发出警告消息的是
sum
,而不是
integrate

Rgames> xf <- 1:10
Rgames> vf <- 4:20
Rgames> sum(xf>vf)
[1] 0
Warning message:
In xf > vf :
 longer object length is not a multiple of shorter object length
Rgames>xf-vf和(xf>vf)
[1] 0
警告信息:
在xf>vf中:
较长的对象长度不是较短对象长度的倍数

您得到的答案不是正确的值这一事实表明,
integrate
没有向函数发送您期望的x向量。

我想说的是:好的观点。也许我们中的一个人应该写一个快速的梯形版本,看看答案是接近300还是6400,但你去改变了一切!:-)。你做了类似的事情来验证这个版本是否正确集成了吗?所以矢量化确实是答案…从我的角度检查了它;-)无论如何,非常感谢!