Plot integral in R -


i'd plot function includes intergral

# intergrand f f <- function(r,x) x*exp(-r)  # integral h <- function(x) {     integrate(f, lower=0, upper=inf, x=x) }  plot(h, xlim=c(-2:4), xlab="x", ylab="y", col="red") 

however, following error message:

error in integrate(f, lower = 0, upper = inf, x = x) :    evaluation of function gave result of wrong length in addition: warning message: in x * exp(-r) :   longer object length not multiple of shorter object length 

i don't understand means. hope have hint me.

there several things going on here.

  1. it looks want integrate on r, not x. integrate(...) integrates f on values of first argument, need switch order of arguments f.
  2. integrate(...) returns list several elements. 1 of these value, value of integral. need refer integrate(...)$value. read the documentation.
  3. if going use plot(...) function, function needs vectorized. is, needs take vector argument , return vector of same length. integrate(...) function 1 of few in r not vectorized. fortunately, there special function, vectorize(...) designed turn scalar-valued functions vectorized functions.

rolling up:

# intergrand f f <- function(r,x) x*exp(-r)   # order of arguments reversed # integral h <- function(x) integrate(f, lower=0, upper=inf, x=x)$value g <- vectorize(h) x <- seq(-2,4,.1) plot(x,g(x), xlim=c(-2,4), xlab="x", ylab="y", col="red") 

as pointed out in other answer, integrating x*exp(-r) on r on [0,inf] yields x, don't see point of doing this. nevertheless, how code works.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -