Re: [Rd] prod(numeric(0)) surprise

From: Thomas Lumley <tlumley_at_u.washington.edu>
Date: Mon 09 Jan 2006 - 19:54:31 GMT

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



R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Tue Jan 10 07:00:00 2006

This archive was generated by hypermail 2.1.8 : Tue 10 Jan 2006 - 04:08:33 GMT