Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex number in R

Tags:

r

I know that you can easily define a complex number z by doing for instance : z <- 3 + 2i. But when I want to define a function that creates a complex number:

f <- function(x,y){
x + yi
}
f(1,2)

I get this error message :

Error in f(1, 2) : object 'yi' not found.

I don't want to use the complex function, because in my case, it is really difficult to find the real and imaginary parts of my complex number.

How can I do ?

like image 936
AdamElKaroui Avatar asked Sep 16 '25 19:09

AdamElKaroui


1 Answers

The i notation will only work with numbers (because a variable in R can't start with a number). Otherwise it will interpret yi as a different variable named "yi" and not convert y to a complex number. Instead, use multiplication explicitly with *

f <- function(x,y){
    x + y * 1i
}
f(1,2)
# [1] 1+2i
like image 156
MrFlick Avatar answered Sep 18 '25 09:09

MrFlick