5

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:

enter image description here

Ok, so not a big deal to do analytically:

enter image description here

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:

enter image description here

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.

1 Answers1

5

Change 3x to 3*x.

(This may be the smallest answer-length-to-question-length ratio I've seen in a long time ;-)

Stephan Kolassa
  • 7,953
  • 2
  • 28
  • 48