Link Search Menu Expand Document (external link)

How to do basic mathematical computations (in R)

See all solutions.


How do we write the most common mathematical operations in a given piece of software? For example, how do we write multiplication, or exponentiation, or logarithms, in Python vs. R vs. Excel, and so on?


For those expressions that need the Python math package, use the code import math beforehand to ensure that package is loaded. Alternatively, you can write from math import * and thus drop the math prefixes in the table below.

Mathematical notation R code
$x+y$ x+y
$x-y$ x-y
$xy$ x*y
$\frac xy$ x/y
$x^y$ x^y
$\vert x\vert$ abs(x)
$\ln x$ log(x)
$\log_a b$ log(b,a)
$e^x$ exp(x)
$\pi$ pi
$\sin x$ sin(x)
$\sin^{-1} x$ asin(x)
$\sqrt x$ sqrt(x)

Other trigonometric functions are also available besides just sin, including cos, tan, etc.

R naturally applies these functions across vectors. For example, you can square all the entries in a vector as in the example below.

example.vector <- c( -3, 2, 0.5, -1, 10, 9.2, -3.3 )
example.vector ^ 2
[1]   9.00   4.00   0.25   1.00 100.00  84.64  10.89

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (