computing an intergral with multiple variables in R - r

Hi I have a equation like the following that I want to calculate.
The equation is given by :
In this equation x is an arrary from 0 to 500.
The value of t = 500 i.e upper limit of the integration.
Now I want to compute c as c(500,x).
The code that I have written so far is as follows:
x <- seq(from=0,by=0.5,length=1000)
t=500
integrand <- function(t)t^(-0.5)*exp((-x^2/t)-t)
integrated <- integrate(integrand, lower=0, upper=t)
final <- pi^(-0.5)*exp(2*x)*integrated
The error I get is as follows:
Error in integrate(integrand, lower = 0, upper = t) :
evaluation of function gave a result of wrong length
In addition: Warning messages:
1: In -x^2/t :
longer object length is not a multiple of shorter object length
2: In -x^2/t - t :
longer object length is not a multiple of shorter object length
3: In t^(-0.5) * exp(-x^2/t - t) :
longer object length is not a multiple of shorter object length
But it doesn't work because there is a variable x inside the integrand which is an arrary. Can anyone suggest how can I compute the integration first and then calculate the total expression for each value of x ? If I change the value of x in the integrand to constant I can compute integration but I want to compute for all the values of x from 0 to 500.
Thank you so much.

Well, here is some code, but it blows up after t=353:
Cfun <- function(XX, upper){
integrand <- function(x)x^(-0.5)*exp((-XX^2/x)-x)
integrated <- integrate(integrand, lower=0, upper=upper)$value
(final <- pi^(-0.5)*exp(2*XX)*integrated) }
sapply(1:400, Cfun, upper=500)

I'd put the loop over values for x outside the integration. Iterate over the x-values and perform the integration for each one inside. Then you'll have C(x) as a function of x suitable for plotting.
You realize, of course, that the indefinite integral can be evaluated:
http://www.wolframalpha.com/input/?i=integrate+exp%28-%28c%2Bt%5E2%29%2Ft%29%2Fsqrt%28t%29
Maybe that will help you see what the answer looks like before you get started.

Related

R integrate function error (simple syntax error I can't find) (Error in integrate(f, a, b) : length(lower) == 1 is not TRUE)

I have a function whose value is the integral of another well-established function. Then I want to create a new function whose value is the integral of the function, whose value is the integral :) The first step is OK, but then the second gives a error. Here's the code:
A <- 1
f <- function(a) a^2
g <- function(a,b) integrate(f,a,b)$value
h <- function(s) g(s,A)
integrate(h,0,A)
The error I get is:
Error in integrate(f, a, b) : length(lower) == 1 is not TRUE
What am I doing wrong? Thanks a lot!
I tried to Google and did not find this specific situation.
I also tried to actually integrate g to obtain h, numerically ad hoc: take dx>0, then dx*sum(sapply(seq(a,b,by=dx),h)) just to obtain a number, but I would like to do it with an integrated function.
The problem is that integrate will not accept an array of values for the lower bound, only a single number. That means your function h(s) cannot accept a vector of values. But integrate also requires that the function to be integrated is vectorized. You can fix this with the function Vectorize.
If you change the definition of h, your code will work.
h <- Vectorize(function(s) g(s,A))
integrate(h,0,A)
0.25 with absolute error < 2.8e-15
Look at the ?integrate
integrate(f, lower, upper)
f should be a function taking a numeric and returning a numeric
your f <- function(a) a^2 is ok.
the next 2 arguments should be the limits of integration ("numbers")
integrate(f,2,5)
39 with absolute error < 4.3e-13
(1/3) * (5^3-2^3)
39
the error message length(lower) == 1 is not TRUE
means that the second argument is not "one" number

R - how to define a "symbolic sequence"

Let's say that we have this sequence of numbers:
1/2, 1/3, 1/4, ..., 1/N
Sorry for the bad formatting, but the LaTeX doesn't work here. Let's say that we define a function which sums all the elements of this sequence:
Σ n = 1N 1/n
The N is supposed to be in the superscipt, but I can't align it properly here - anyway, this function would calculate the sum of all 1/n elements starting from n=1 to N.
I now want to find the limit of this function when N tends to infinity using R. For this, I was planning to use the lim function from the Ryacas package as suggested in this question.
However, I can't seem to find a way to make my script work. My idea was this:
x <- ysym("x")
sq <- 1:x
fun <- sum(1/sq)
lim(fun, x, Inf)
However, I am already getting an error at the second step of this process. I can't seem to run the
sq <- 1:x:
Error in 1:x : NA/NaN argument
In addition: Warning message:
In 1:x : numerical expression has 3 elements: only the first used
So it seems that it's not possible to define a "symbolic sequence" (don't know what else I would call it) in this way.
What would be the proper way to calculate what I want?
This series goes to infinity:
library(Ryacas)
yac_str("Sum(n, 1, Infinity, 1/n)")
# "Infinity"
Let's try a convergent series:
yac_str("Sum(n, 1, Infinity, 1/n^2)")
# "Pi^2/6"
If you really want to use Limit:
yac_str("Limit(n, Infinity) Sum(i, 1, n, 1/i^2)")
Use yac_str to execute a Yacas command.

optim function with a vector of parameters in R

I need to find a beta (3-element vector) which minimizes QRsum, defined as below:
#indicator function
I=function(x,min,max){
if (min<=x && x<max){i=1} else {i=0}}
#QR check function
rho=function(a, theta){
return(abs(theta-I(a,-Inf,0))*abs(a))
}
#QR sum
QRsum=function(beta,y,X,theta){
sum=0
for (i in 1:length(y)){
sum=sum+rho(y[i]-t(X[i,])%*%beta,theta)
}
sum=1/length(y)*sum
return(sum)
}
result=optim(initial_beta,QRsum(beta,y,X,0.05),method="BFGS")
Running optim function finished with following message:
Browse[1]> Q
> result=optim(initial_beta[1,],fn=QRsum(beta[1,],y,X,0.05),method="BFGS")
Error in (function (par) : could not find function "fn"
Arguments of QRsum are y-a vector, X - a matrix with 3 columns and beta - a vector of 3 elements which should be optimized. QRsum function works fine when calling, but here it somehow fails. Is y and X are the objects I defined earlier or they are unknown also despite I defined them before? What should I put as first argument of my function - arbitrary value of a vector?
I must say that I use optim for the very first time, so I suppose I'm missing something here, but I can't figure out what exactly based on help.
You need to modify the call of the optim package to the following:
# define some data / value with which you want to use in the optimization
y_val <- ...
X_val <- ...
theta_val <- 0.05
# call optim / optimize beta with given values for y, X and theta
optim(par=initial_beta, fn=QRsum, y=y_val, X=X_val, theta=theta_val, method="BFGS")

Integrand Syntax in R

I'm trying to complete a straightforward integration, but I'm running into an issue that (I think) is due to the form in which I'm writing the integrand.
Suppose I want to find the area bound by f(x) = 3x and g(x) = x^2. Geometrically, the area between the two curves:
Ok, so not a big deal to do analytically:
But I'd like to accomplish this with R, of course.
So I enter my function and there's a problem:
> g <- function(x) {3x-x^2}
Error: unexpected symbol in "g <- function(x) {3x"
This frustrated me so I started playing around with things. Interestingly, I found that if I factor x out of the integrand:
everything works smoothly:
> f <- function(x) {x*(3-x)}
> integrate(f, 0, 3)
4.5 with absolute error < 5e-14
My next step was to check ?integrate, part of which is attached below:
integrate(f, lower, upper, ..., subdivisions = 100L,
rel.tol = .Machine$double.eps^0.25, abs.tol = rel.tol,
stop.on.error = TRUE, keep.xy = FALSE, aux = NULL)
Arguments
f
an R function taking a numeric first argument and returning a numeric vector of the same length. Returning a non-finite element will generate an error.
lower, upper
the limits of integration. Can be infinite.
Am I somehow not taking a numeric first argument in my first attempt to integrate? Thanks in advance.
Change 3x to 3*x.
(This may be the smallest answer-length-to-question-length ratio I've seen in a long time ;-)

kernel density bandwidth in R

I have two vectors: 1) ~1000 sample means and 2) the corresponding ~1000 standard deviations of those means. I would like to create a kernel density plot of these data, using the sample means as the observations from which density is estimated, and the standard deviations of each mean as the bandwidth for each observation. Problem is, density only allows a vector of length 1 to be used as a bandwidth. For example:
plot(density(means,bw=error))
returns the following warnings:
1: In if (!is.finite(bw)) stop("non-finite 'bw'") :
the condition has length > 1 and only the first element will be used
2: In if (bw <= 0) stop("'bw' is not positive.") :
the condition has length > 1 and only the first element will be used
3: In if (!is.finite(from)) stop("non-finite 'from'") :
the condition has length > 1 and only the first element will be used
4: In if (!is.finite(to)) stop("non-finite 'to'") :
the condition has length > 1 and only the first element will be used
...and I get a plot that uses the error of the first item in the list as the bandwidth for all of my observations.
Any ideas on how I could implement a separate, user-defined bandwidth for each observation used to produce a kernel density plot?
It doesn't look like density supports this sort of bandwidth specification. I suppose you could roll your own by
mydensity <- function(means, sds) {
x <- seq(min(means - 3*sds), max(means + 3*sds), length.out=512)
y <- sapply(x, function(v) mean(dnorm(v, means, sds)))
cbind(x, y)
}
This will be a good deal slower than the real function (which appears to use fft in the computation). Here it is at work, with small bandwidths at the left and large at the right:
set.seed(144)
means <- runif(1000)
sds <- ifelse(means < 0.5, 0.001, 0.05)
plot(mydensity(means, sds))

Resources