# Integral formula using R

I have to implement this formula:

$K(x) = \int_{0}^{0.5}q_{\theta}(x)d{\theta}$

where $q_{\theta}(x)$´s are the conditional quantiles in some $\theta$.

using a range of $\theta = [0.45; 0.40; 0.35; 0.3; 0.25; 0.2; 0.15; 0.1; 0.05]$

Note that i am integrating in $\theta$ not in $x$.

The idea is, when im in $\theta=.05$ i automatically have $q_{.05}(x)$ through:

q_theta<-rq(Y~x,tau = .05)


and so on through in the interval $\theta = [0.45; 0.40; 0.35; 0.3; 0.25; 0.2; 0.15; 0.1; 0.05]$.

q_theta<-rq(Y~x,tau = .45)
q_theta<-rq(Y~x,tau = .35)
q_theta<-rq(Y~x,tau = .3)
q_theta<-rq(Y~x,tau = .25)
q_theta<-rq(Y~x,tau = .2)
q_theta<-rq(Y~x,tau = .15)
q_theta<-rq(Y~x,tau = .1)


And i proceed to the integration, where i have no idea how to do:

My data:

set.seed(33)
N<-100
Y<- rnorm(N,0,3)
x<- runif(N)


And then, i calculate: $K(x) = \int_{0}^{0.5}q_{\theta}(x)d{\theta}$

I hope I have been clear, otherwise I redo the question.

I dont know how to build this integral function.

Any sugestion?

Thanks.

I guessed $d\theta$ to be $dx$. Because I can't conclude Y to be a fixed vector, I used x and y as integral function's arguments.

integrate(f, lower, upper, ...) is adaptive quadrature of functions of one variable over a finite or infinite interval. f is an R function taking a numeric first argument and returning a numeric vector of the same length.

library(quantreg)

# explanatory simple function (this function can treat only one theta)
K0 <- function(x, y){
temp <- rq(y ~ x, tau = theta)$coef - rq(y ~ x, tau = .50)$coef
f <- function(x) temp + temp * x
integrate(f, 0, 0.5)
}
# rq(Y ~ x, tau = theta)$coef are it's coefficients. # Because of a primary expression, ~ is a intercept, ~ is a slope. # The same is true of (q_theta$coef - q_theta_50$coef), so make it a function(x) to integrate. set.seed(33) N<-100 Y<- rnorm(N,0,3) x<- runif(N) # the same length of x and y is essential one_theta <- 0.9 K0(x = x, y = Y) # 1.604942 with absolute error < 1.8e-14 # improvement to treat multi theta K <- function(x, y){ temp <- NULL for(i in seq.int(theta)) temp <- rbind(temp, rq(y ~ x, tau = theta[i])$coef - rq(y ~ x, tau = .50)$coef) temp2 <- apply(temp, 1, function(a) { f <- function(x) a + a * x integrate(f, 0, 0.5) }) names(temp2) <- paste0("theta = ", theta) temp2 } theta <- c(0.99, 0.975, 0.95, 0.90, 0.85, 0.80, 0.75) K(x = x, y = Y) # : #$theta = 0.9
# 1.604942 with absolute error < 1.8e-14

# \$theta = 0.85
# 1.148646 with absolute error < 1.3e-14
# :