[R] Sweave and complex numbers

Duncan Murdoch murdoch at stats.uwo.ca
Mon Jul 11 14:02:27 CEST 2005


Robin Hankin wrote:
> Hi
> 
> When using Sweave, most of my functions get called with complex  
> arguments.
> 
> They get typeset in with additions that I don't want; "1+1i" appears  
> as "1 + (0 + 1i)"
> and I would rather have plain old "1+1i".
> 
> Example follows:
> 
> 
> 
> 
> \documentclass[a4paper]{article}
> 
> \title{A Test File}
> \author{Robin Hankin}
> 
> \usepackage{a4wide}
> 
> \begin{document}
> 
> \maketitle
> 
> A simple example:
> <<print=TRUE>>=
> f <- function(x){
> x+c(1,1+1i)}
> f(6+7i)
> @
> 
> 
> Question: why does \verb=c(1,1+1i)= get printed as
> \verb=c(1,1 + (0+1i))= ?
> 
> And how can I stop it?
> 
> \end{document}
> 
> 
> 
> 
> can anyone help me here?

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 "+".

Maybe someone else has an answer to your 2nd question.

Duncan Murdoch




More information about the R-help mailing list