[Rd] Bug or a feature that I completely missed?

Gabor Grothendieck ggrothendieck at gmail.com
Wed Nov 16 03:39:22 CET 2005


On 11/15/05, Berwin A Turlach <berwin at maths.uwa.edu.au> wrote:
> Dear all,
>
> while looking at some R-code submitted by students in a unit that I
> teach, I came across constructs that I thought would lead to an error.
> Much to my surprise, the code is actually executed.
>
> A boiled down version of the code is the following:
>
> > tt <- function(x, i){
> +   mean(x[i,2])/mean(x[i,1])
> + }
> > dat <- matrix(rnorm(200), ncol=2)
> > mean(dat[,2])/mean(dat[,1])
> [1] -1.163893
> > dat1 <- data.frame(dat)
> > tt(dat1)                 ###  Why does this work?
> [1] -1.163893
> > tt(dat)
> Error in mean(x[i, 2]) : argument "i" is missing, with no default
>
> Since the data for the assignment was in a data frame, the students got
> an answer and not an error message when they called the equivalent of
> tt(dat1) in their work.
>
> I tested this code on R 1.8.1, 1.9.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1,
> 2.2.0 and R-devel (2005-11-14 r36330), all with the same result, no
> error message when executing tt(dat1).
>
> I would have expected that tt(dat1) behaves in the same way as tt(dat)
> and would produce an error.  Thus, I think it is a bug, but the fact
> that so many R versions accept this code makes me wonder whether it is
> a misunderstanding on my side.  Can somebody enlighten me why this
> code is working?
>

I don't have a complete explanation but consider:

f <- function(x) missing(x)
g <- function(x) f(x)
g()  # TRUE

That is, in R one can pass missing values from one
function to another and that is evidently what
is happening with tt which passes the missing
i to [.data.frame.  The weird part, to me, is that
[ does not also allow this even though it does allow
empty arguments though likely its due to
[ being written in C and [.data.frame being
written in R.

Try

getAnywhere("[.data.frame")
getAnywhere("[")



More information about the R-devel mailing list