我正在尝试对一系列值的概率分布进行数值积分。这应该看起来像这样。例如,我想使用指数概率分布函数来做到这一点(https://en.wikipedia.org/wiki/Exponential_distribution,http://homepages.math.uic.edu/~jyang06/stat401/讲义/handout8.pdf):
## define the integrated function (for lambda = 2)
integrand <- function(x) {2 * 2.718^(-2*x)}
upper = seq(0, 5, by = 0.01)
lower = 0
data = data.frame(lower,upper)
data$integral = integrate(integrand, lower = data$lower, upper = data$upper)
不幸的是,我收到了这个错误:
Error in integrate(integrand, lower = my_data$lower, upper = my_data$upper) :
length(lower) == 1 is not TRUE
这很奇怪,因为否则积分功能可以正常工作:
> integrate(integrand, lower = 0, upper = 0.01)
0.02020132 with absolute error < 2.2e-16
> integrate(integrand, lower = 0, upper = 0.06)
0.127496 with absolute error < 1.4e-15
谢谢!
试试这个
data$integral <- apply(data, 1, function(x) {integrate(integrand, lower = x[1], upper = x[2])$value})
head(data)
lower upper integral
1 0 0.00 0.00000000
2 0 0.01 0.02020132
3 0 0.02 0.04081069
4 0 0.03 0.06183635
5 0 0.04 0.08328672
6 0 0.05 0.10517036
以防万一有人遇到与我遇到的类似问题并出现此错误...... 我试图对我的数据运行集成函数:
sei <- function(t = 1) exp(-t)/t # standard exponential integral
alpha <- vegan::fisherfit(data)$estimate # alpha estimate
N <- sum(data) # number of observations
rank.logseries <- sapply(data, function(x) {
logeqn <- x * log(1 + alpha/N)
f<-integrate(sei, logeqn, Inf)
fv<-f[["value"]]
alpha*fv
})
我也遇到了同样的错误。我意识到问题是我的数据是单列数据框。 一旦我澄清了这一点,集成就完美地工作了。
sei <- function(t = 1) exp(-t)/t # standard exponential integral
alpha <- vegan::fisherfit(data)$estimate # alpha estimate
N <- sum(data) # number of observations
rank.logseries <- sapply(data[,1], function(x) {
logeqn <- x * log(1 + alpha/N)
f<-integrate(sei, logeqn, Inf)
fv<-f[["value"]]
alpha*fv
})