3
 constant <- function(x){1}

 integrate(constant,lower=1,upper=10)

this is probably more than ridiculously simple, but any reason as to why this isn't working?

is there a different way I should be writing the function for constants?

4

2 回答 2

7

您可以使用该Vectorize函数将非矢量化函数转换为integrate需要的函数类型:

> constant <- function(x){1}
> Vconst <- Vectorize(constant)
>  integrate(Vconst,lower=1,upper=10)
9 with absolute error < 1e-13
于 2012-08-23T23:34:38.443 回答
2

来自?integrate

一个 R 函数,采用数字第一个参数并返回相同长度的数字向量。返回非有限元素将产生错误。

您需要返回一个与 x 长度相同的向量。尝试:

constant <- function(x){rep(1,length(x))}
于 2012-08-23T23:29:12.693 回答