[R] Behavior of [[ in S vs. R

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Oct 18 11:08:37 CEST 2003


On Fri, 17 Oct 2003, Thomas Lumley wrote:

> On Fri, 17 Oct 2003, Backlund, Jan Erik (JE) wrote:
>
> > I am confused by the following difference in the behavior of R and S. Any
> > clarification would be greatly appreciated.
>
> sw[[2,1]] in R is short for sw[[2]][[1]], which in the case of a data
> frame is sw[1,2], as your example shows.

For a data frame only, that is.  In S-PLUS it is equivalent to
sw[[1]][[2]]. Neither system documents exactly what they do, AFAICS.
S-PLUS 6.1 says `[[ is designed to subscript lists'.  R does say

     When '[' and '[[' are used with two indices they act like indexing
     a matrix:  '[[' can only be used to select one element.

which suggests that the R difference is unintentional.

You will find that sw[[c(2,1)]] works the same in both systems.

R needs to either document more clearly what it does or change its
behaviour to conform to the (naive reading of the) documentation (and I
would prefer the second).

[...]

Example of `for data frame only'

> foo <- list(a=list(A=1, B=2), b=list(C=3, D=4))
> foo[[2]][[1]]
[1] 3
> foo[[2,1]]
Error in foo[[2, 1]] : incorrect number of subscripts
> foo[[c(2,1)]]
[1] 3

although ?"[[" does show x[[i, j, ...]] as a usage.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list