gpt4 book ai didi

r - 当我使用函数 "integrate"时 R 中的集成问题

转载 作者:行者123 更新时间:2023-12-04 15:30:51 24 4
gpt4 key购买 nike

我正在尝试使用生成的数据集计算一种 Gini 指数。但是,我在最后一个集成功能中遇到了问题。如果我尝试集成名为 f1 的函数,R 说

Error in integrate(Q, 0, p) : length(upper) == 1 is not TRUE 

我的代码是

# set up parameters b>a>1 and the number of observations n
n <- 1000
a <- 2
b <- 4

# generate x and y
# where x follows beta distribution
# y = 10x+3
x <- rbeta(n,a,b)
y <- 10*x+3

# the starting point of the integration having problem
Q <- function(q) {
quantile(y,q)
}

# integrate the function Q from 0 to p
G <- function(p) {
integrate(Q,0,p)
}

# compute a function
L <- function(p) {
numer <- G(p)$value
dino <- G(1)$value
numer/dino
}

# the part having problem
d <- 3
f1 <- function(p) {
((1-p)^(d-2))*L(p)
}
integrate(f1,0,1) # In this integration, the aforementioned error appears

我认为,重复的集成可能会产生问题,但我不知道确切的问题是什么。请帮助我!

最佳答案

@John Coleman 所述, integrate 需要有一个矢量化函数和一个适当的 subdivisions 选项来完成积分任务。即使您已经为积分提供了矢量化函数,有时也很难在 integrate(...,subdivisions = ) 中正确设置 subdivisions

为了解决你的问题,我推荐 pracma 包中的 integral,其中你仍然是积分的矢量化函数(参见我对函数 GL),但不需要手动设置分割,即

library(pracma)

# set up parameters b>a>1 and the number of observations n
n <- 1000
a <- 2
b <- 4

# generate x and y
# where x follows beta distribution
# y = 10x+3
x <- rbeta(n,a,b)
y <- 10*x+3

# the starting point of the integration having problem
Q <- function(q) {
quantile(y,q)
}

# integrate the function Q from 0 to p
G <- function(p) {
integral(Q,0,p)
}

# compute a function
L <- function(p) {
numer <- Vectorize(G)(p)
dino <- G(1)
numer/dino
}

# the part having problem
d <- 3
f1 <- function(p) {
((1-p)^(d-2))*L(p)
}

res <- integral(f1,0,1)

然后你会得到

> res
[1] 0.1283569

关于r - 当我使用函数 "integrate"时 R 中的集成问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61270261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com