Integral Calculator in R

I know how to use integral calculator to obtain numeric values, but don't know how to get an algebraic equation.

For example:

integrand <- function(x) {1/((x+1)*sqrt(x))}
integrate(integrand, lower = 0, upper = Inf)

with this code, I can get 3.141593 with absolute error < 2.7e-05

However, what if I want to use this code:

integrand <- function(x) {2*x}
integrate(integrand, lower = -Inf, upper = Inf)

to get x^2.

Apparently, it does not work.

If someone can help this, I would appreciate your help. Tons of thanks!

2

1 Answer

R doesn't do symbolic math but there are R packages that do. I will give (very) short examples using CRAN packages Ryacas and rSympy.

1. Package Ryacas.

library(Ryacas)

f <- ysym("2*x")
integrate(f, "x")
#y: x^2

2. Package rSymPy.

With package rSymPy you need to define the symbol "x" first. This is done with function Var.
Note: in my tests, the first time any of Var or sympy were called a series of warnings were given. I have interrupted R and at the second time all went well.

library(rSymPy)

x <- Var("x")
sympy("integrate(2*x)")
#[1] "x**2"
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest