Skip to content
Prev 174977 / 398506 Next

"[.data.frame" and lapply

Hi,

This is a bug I think. [.data.frame treats its arguments differently 
depending on the number of arguments.

 > d <- data.frame(x = rnorm(5), y = rnorm(5), z = rnorm(5) )
 > d[, 1:2]
             x           y
1   0.45141341  0.03943654
2  -0.87954548  1.83690210
3  -0.91083710  0.22758584
4   0.06924279  1.26799176
5  -0.20477052 -0.25873225
 > base:::`[.data.frame`( d, j=1:2)
             x           y          z
1   0.45141341  0.03943654 -0.8971957
2  -0.87954548  1.83690210  0.9083281
3  -0.91083710  0.22758584 -0.3104906
4   0.06924279  1.26799176  1.2625699
5  -0.20477052 -0.25873225  0.5228342
but also:
 > d[ j=1:2]
            x           y          z
1  0.45141341  0.03943654 -0.8971957
2 -0.87954548  1.83690210  0.9083281
3 -0.91083710  0.22758584 -0.3104906
4  0.06924279  1.26799176  1.2625699
5 -0.20477052 -0.25873225  0.5228342

`[.data.frame` only is called with two arguments in the second case, so 
the following condition is true:

if(Narg < 3L) {  # list-like indexing or matrix indexing

And then, the function assumes the argument it has been passed is i, and 
eventually calls NextMethod("[") which I think calls 
`[.listof`(x,i,...), since i is missing in `[.data.frame` it is not 
passed to `[.listof`, so you have something equivalent to as.list(d)[].

I think we can replace the condition with this one:

if(Narg < 3L && !has.j) {  # list-like indexing or matrix indexing
 
or this:

if(Narg < 3L) {  # list-like indexing or matrix indexing
        if(has.j) i <- j
  
 > `[.data.frame`(d, j=1:2)
            x           y
1  0.45141341  0.03943654
2 -0.87954548  1.83690210
3 -0.91083710  0.22758584
4  0.06924279  1.26799176
5 -0.20477052 -0.25873225

However, we would still have this, which is expected (same as d[1:2] ):

 > `[.data.frame`(d, i=1:2)
            x           y
1  0.45141341  0.03943654
2 -0.87954548  1.83690210
3 -0.91083710  0.22758584
4  0.06924279  1.26799176
5 -0.20477052 -0.25873225

Romain
baptiste auguie wrote: