Reputation: 155
I'm trying to apply ks.test
test to a group of data and a custom CDF. The CDF has the following form:
my_cdf <- function(x) integrate(my_pdf, 0, x, subdivisions=2000)$value
where my_pdf
is a function that takes a single value as the argument.
Now, in order to use ks.test
, I need my_cdf
to produce a vectorized output given a vector input. How should I do that?
Example my_pdf
(It is not a real PDF but that should not matter):
my_pdf <- function(y) y + 1
Example objective:
my_cdf(c(1,2,3))
[1] 1.5 4 7.5
Upvotes: 0
Views: 56
Reputation: 269870
Use Vectorize
to transform my_cdf
into a vectorized version:
my_cdfv <- Vectorize(my_cdf)
my_cdfv(1:3)
## [1] 1.5 4.0 7.5
Upvotes: 3
Reputation: 174293
You can use sapply
. Personally, I would allow any pdf to be supplied to the function
my_cdf <- function(x, pdf)
{
sapply(x, function(y) integrate(pdf, 0, y, subdivisions=2000)$value)
}
So we can do:
my_pdf <- function(y) y + 1
my_cdf(c(1, 2, 3), pdf = my_pdf)
#> [1] 1.5 4.0 7.5
or
my_cdf(c(0.1, 0.5, 1), pdf = dnorm)
#> [1] 0.03982784 0.19146246 0.34134475
If you're sure you'll never need to supply a different pdf, then you can just do
my_cdf <- function(x) sapply(x, function(y) integrate(my_pdf, 0, y, subdivisions=2000)$value)
Upvotes: 1