R Complex Numbers
R has built-in support for complex numbers, letting you write values with a real and an imaginary part using the i suffix and compute with them directly.
Writing a Complex Number
Attach the letter i directly after a number to mark it as an imaginary part, and combine it with a real part to build a full complex number, such as 3 + 2i. R stores this as its own dedicated type, complex.
Example
z <- 3 + 2i
class(z)
# "complex"
print(z)
# 3+2iExtracting the Parts of a Complex Number
Re() and Im() pull out the real and imaginary components, Mod() returns the magnitude (the distance from zero, computed with the Pythagorean theorem), and Conj() returns the complex conjugate — the same number with the sign of the imaginary part flipped.
Example
z <- 3 + 4i
Re(z) # 3
Im(z) # 4
Mod(z) # 5
Conj(z) # 3-4iArithmetic with Complex Numbers
The usual arithmetic operators work directly on complex numbers and follow the standard rules of complex-number math, so you can add, subtract, multiply, and divide them exactly like any other numeric value.
Example
(1 + 2i) + (3 + 1i)
# 4+3i
(1 + 2i) * (2 + 0i)
# 2+4iBuilding Complex Vectors
The complex() function constructs complex numbers from separate real and imaginary vectors, which is convenient when you need to generate many values at once instead of typing each one out with an i suffix.