R Language: Atomic types: Complex
If you're going to program in R, then you need to understand the atomic data types: logical, integer, real, complex, character and raw. Let's look at complex numbers in R.
First, a quick review. Complex numbers are a combination of a real number and an imaginary number. Real numbers are easy: integers and fractionals are real numbers. Imaginary numbers are also easy(?): the square root of -1 (sort of).
How do you write a complex number in R? Here's some code...
> I.am.complex <- 3i
> class(I.am.complex)
[1] "complex"
> I.am.complex <- 1 + 2i
> I.am.complex <- -1 + 0i
> as.complex(3)
[1] 3+0i
Just add the letter "i" to a number - or use as.complex(). Most R functions know how to handle complex (and imaginary) numbers.
> sqrt(I.am.complex)
[1] 0+1i
> -1+0i == as.complex(-1)
[1] TRUE
> as.complex(3)
[1] 3+0i
Easy and quick!
Of course, what you do with complex numbers is your deal. Let me know if you depend on them.
Need more? Here's the R weekly session on atomic types...
By the way...
I cover stuff like this every week. Check out R for Data Science: Lunchbreak Lessons.