R, Integrate at each point of array

断了今生、忘了曾经 提交于 2019-12-12 04:37:01

问题


I'm stuck with computing the integral at each point of an array. The idea is first to create a function ("Integrand"). Then, create a second function ("MyConvolve") that computes the necessary integral.

Here's what I did up to now:

Integrand = function(s,x)
{ 1/4*(abs(x-s)<=1)*(abs(s)<=1) }

MyConvolve = function(func,data)
{ return( integrate(func, lower=-Inf, upper=Inf, data) ) }

Now, running the code with some array, I get an error message:

SomeMatrix = replicate(10, rnorm(10))
MyConvolve(Integrand, SomeMatrix)

Which ends up with the following error message:

Error in integrate(func, lower = -Inf, upper = Inf, data) :
evaluation of function gave a result of wrong length

I already tried vectorizing the function, but still ended up with error messages.

Thank you very much for your help!


回答1:


I am not sure I understand what you are trying to compute, but if you want to evaluate MyConvolve(Integrand,s), where s takes all the values in SomeMatrix, then apply is sufficient.

sapply( SomeMatrix, function(s) MyConvolve( Integrand, s )$value )

However, the dimensions of the matrix are lost. You can recover them as follows:

result <- SomeMatrix
result[] <- sapply( SomeMatrix, function(s) MyConvolve( Integrand, s )$value )


来源:https://stackoverflow.com/questions/15921090/r-integrate-at-each-point-of-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!