integrate関数を使う。引数は次のとおり。
integrate(関数, 積分の下端, 積分の上端)
関数はfunction関数で定義しておくこと。以下は、x^2を0から1まで、0から2まで積分した例。手計算で定積分はそれぞれ1/3,8/3である。
> f <- function(x) x ^ 2
> integrate(f, 0, 1)
0.3333333 with absolute error < 3.7e-15
> integrate(f, 0, 2)
2.666667 with absolute error < 3e-14
三角関数などのように定義済みの関数はそのままでも使うことができる。既存の関数を使用して関数を定義することもできる。
> integrate(cos, 0, pi / 2)
1 with absolute error < 1.1e-14
> f <- function(x) cos(x)
> integrate(f, 0, pi / 2)
1 with absolute error < 1.1e-14
置換積分法を使わなければ解けないような積分も、簡単に行える。下記の例では、手計算で定積分は8/sqrt(2)=5.656854…である。
> f <- function(x) 4 * cos(x / 2)
> integrate(f, 0, pi / 2)
5.656854 with absolute error < 6.3e-14