[R] Sweave and complex numbers

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Jul 11 15:04:52 CEST 2005

Duncan Murdoch <murdoch at stats.uwo.ca> writes:

> > Question: why does \verb=c(1,1+1i)= get printed as
> > \verb=c(1,1 + (0+1i))= ?
> The R parser only understands pure imaginary constants as complex 
> numbers.  It parses 1+1i as the sum of the real constant 1 and the 
> complex constant 0+1i.
> This isn't easy to work around.  Sweave could special case these, or the 
> parser or deparser could, but it looks messy to me.  I'd guess the best 
> solution would be if it happened in the parser (i.e. a real constant 
> plus an imaginary constant was folded into a complex constant), but 
> right now our parser doesn't do any sorts of optimizations like this. 
> It's not easy to add the first one, not least because the parser doesn't 
> know for sure that 1+1i really is a complex number:  you might have 
> redefined the meaning of "+".

Hmmmm... I'd say that the user would deserve what she gets in that
case. I suspect that the real issue is that R's tokenizer is
hand-written and not smart enough to recognize complex constants.
Figuring out whether there is a good reason for that or whether we
might actually use an automatic tokenizer like flex is somewhere on
the far end of my want-to-do list...

One thing that could be done quite immediately is to let the deparser
forget about a zero real part and drop the parentheses in that case.
After all "1i" is perfectly legal R, and

> identical(1i,0+1i)
[1] TRUE

(Those parse/deparse asymmetries are maddening. *Next* time we
redesign R we should get this straightened out....)

   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907

More information about the R-help mailing list