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:
Syntax
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
z <- 3 + 4i
cat(class(z), "\n")
cat("Magnitude:", Mod(z), "\n")
cat("Real part:", Re(z), "Imaginary part:", Im(z), "\n")
Login to try C/C++/Java/PHP code in the editor
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
- Writing
3 + i4or3 + 4*iinstead of3 + 4i, which fails becauseimust directly follow the number. - Expecting
sqrt(-1)to give1i, when it returnsNaNwith a warning unless you usesqrt(as.complex(-1)). - 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: