From tlumley at u.washington.edu  Mon Jan  9 20:54:31 2006
From: tlumley at u.washington.edu (Thomas Lumley)
Date: Mon, 9 Jan 2006 11:54:31 -0800 (PST)
Subject: [Rd] prod(numeric(0)) surprise
In-Reply-To: <6phirstz2pi.fsf@gopher3.fhcrc.org>
References: <43C1C973.8080702@zoo.ufl.edu> <43C1CBB9.7090307@stats.uwo.ca>
	<43C1CD05.2030504@zoo.ufl.edu>
	<17346.5951.435355.767827@stat.math.ethz.ch>
	<6phslrxz4dg.fsf@gopher3.fhcrc.org> <43C2A149.5030903@stats.uwo.ca>
	<6phirstz2pi.fsf@gopher3.fhcrc.org>
Message-ID: <Pine.LNX.4.64.0601091046090.29697@homer23.u.washington.edu>

On Mon, 9 Jan 2006, Martin Morgan wrote:

> I guess I have to say yes, I'd exepct
>
> x <- 1:10
> sum(x[x>10]) ==> numeric(0)
>
> this would be reinforced by recongnizing that numeric(0) is not zero,
> but nothing. I guess the summation over an empty set is an empty set,
> rather than a set containing the number 0. Certainly these
>
> exp(x[x>10]) ==> numeric(0)
> numeric(0) + 1 ==> numeric(0)
>

There are some fairly simple rules in how R does it.  You do need to 
distinguish between functions (binary operators) that map two vectors of 
length n to a vector of length n and functions such as prod and sum that 
map a vector of length n to a vector of length 1.

The output of sum and prod is always of length 1, so sum(numeric(0)) and 
prod(numeric(0)) should be of length 1 (or give an error).  It is 
convenient that sum(c(x,y)) is equal to sum(x)+sum(y) and that 
prod(c(x,y)) is equal to prod(x)*prod(y), which motivates making 
sum(numeric(0)) give 0 and prod(numeric(0)) give 1.

Single argument functions such as exp(numeric(0)) seem fairly obvious: you 
have no numbers and you exponentiate them so you still have no numbers. 
You could also argue based on c() and exp() commuting.

The rules for binary operators are a little less tidy [my fault]. They 
come from the idea that x+1 should always add 1 to each element of x.  If 
you add 1 to each element of numeric(0) you get numeric(0).  The usual 
recycling rule says that the shorter vector should be repeated to make it 
the same length as the longer vector, so this is a wart.  On the other 
hand, you can't recycle a vector of length 0 to have length 1, so the 
usual recycling rule can't be applied here. This also makes matrix 
operations work, at least in the sense of getting 
matrices of the right dimension.

 	-thomas



[Rd] prod(numeric(0)) surprise
Thomas Lumley