← Back to R Course | Chapter 2: Variables & Types | Lesson 6 of 7

Complex Type

Complex numbers have two parts, an everyday part and an imaginary part, like a treasure map with two coordinates. R can do math with them directly, which is useful in science and engineering.

In this page:

  1. Complex Type
Syntax
r
z <- 3+2i
Re(z)
Im(z)

Complex Type

R natively supports complex numbers with the complex type, written as a+bi using i for the imaginary unit, like 3+4i.

Standard arithmetic operators work directly on complex numbers. This is less commonly used than the other basic types but is fully built in for scientific and engineering computation.

Note: Mod() computes a complex number's magnitude, and Re()/Im() extract its real and imaginary parts.

Example: Complex Type

markup
z <- 3 + 4i

cat(class(z), "\n")
cat("Magnitude:", Mod(z), "\n")
cat("Real part:", Re(z), "Imaginary part:", Im(z), "\n")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing 3 + i4 or 3 + 4*i instead of 3 + 4i, which fails because i must directly follow the number.
  2. Expecting sqrt(-1) to give 1i, when it returns NaN with a warning unless you use sqrt(as.complex(-1)).
  3. Comparing complex numbers with < or >, which is an error because they have no order.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.