[R] help with integration

Uwe Ligges ligges at statistik.tu-dortmund.de
Wed Mar 4 16:20:36 CET 2009



andrea.toreti at apat.it wrote:
> Dear all,
> I have a problem with the integration of the following function.
> Could you please give some suggestions?
> 
> Thank you very much!!!
> 
> y<-rnorm(n=100)
> 
> f<-function(x,xi,h){
>  n<-length(xi)
>  Ke<-c()
>  for(t in 1:n) {
>   Ke[t]<-dnorm((x-xi[t])/h)
>  }
>  fke<-sum(Ke)*(1/(n*h))
>  fke<-fke^2
>  return(fke)
> }
> integrate(f,-Inf,Inf,xi=y,h=0.32)


integrate expects to work on a function f that works on a vector of x 
values (rather than just a scalar x), hence you probably want (somewhat 
rewritten):

f <- function(x, xi, h){
  n <- length(xi)
  Ke <- dnorm((x - xi) / h)
  fke <- sum(Ke) * (1 / (n*h))
  return(fke^2)
}

f2 <- function(x,xi,h){
     sapply(x, f, xi = xi, h = h)
}

integrate(f2, -Inf, Inf, xi=y, h=0.32)



Uwe Ligges




> I obtained this error:
>   evaluation of function gave a result of wrong length
> In addition: There were 50 or more warnings (use warnings() to see the 
> first 50)
> 50: In Ke[t] <- dnorm((x - xi[t])/h) :
>   number of items to replace is not a multiple of replacement length
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list