Justin Bloesch
Justin Bloesch

Reputation: 13

Quantile from given function R Code Error?

I am using R to get quantile from a given function which is giving the error below which I don't quite understand what it means. Although the error message seems self explanatory this R Noob can't work it out. Any help appreciated.

Error:

Error in cum(x) - p : non-numeric argument to binary operator

Here is the code:

library(nleqslv)

dens<-function(x)
{
  (dbeta(x, shape1 = 1, shape2 = 5) + dbeta(x, shape1 = 3, shape2 = 5) + dbeta(x, shape1 = 10, 
  shape2 = 5))*1/3
}

cum<-function(x)
{
    integrate(dens,-Inf,x)
}

quant<-function(p)
{
    nleqslv(0, function(x){cum(x)-p})
}


print(quant(0.50))

Upvotes: 1

Views: 95

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226761

integrate() doesn't return a single number, but a list:

names(cum(1))
## [1] "value"        "abs.error"    "subdivisions" "message"      "call"   

All you need is the $value element:

quant <- function(p) {
    nleqslv(0, function(x) { cum(x)$value-p })
}

(Since you're adding up dbeta() values maybe the lower limit of your integral can be 0 instead of -Inf ?)

Upvotes: 1

Related Questions