Mohammad
Mohammad

Reputation: 1098

how to read a string as a complex number?

I have a string which has a complex format, how can I use complex() to treat it as a complex number? For example:

myStr="0.76+0.41j"

now I want to do sth like:

myStr_complex=complex(myStr) # my question is how should I do this part?

Eventually

Im(myStr_complex)

should print

0.41

Upvotes: 1

Views: 172

Answers (1)

MrFlick
MrFlick

Reputation: 206197

R prefers to use i rather than j. Aslo note that complex is different than as.complex and the latter is used for conversion. You can do

myStr <- "0.76+0.41j"
myStr_complex  <- as.complex(sub("j","i",myStr))
Im(myStr_complex)
# [1] 0.41

Upvotes: 6

Related Questions