[Rd] Strange behaviour of the [[ operator

Seth Falcon sfalcon at fhcrc.org
Sat Sep 30 18:38:31 CEST 2006


Martin Maechler <maechler at stat.math.ethz.ch> writes:
>     >> a <- list(b=5)
>     >> a[['b']]
>     Herve> [1] 5
>     >> a[[t<-'b']]
>
>     Herve> Nothing gets printed!
>
> Yes, but that is not really much related to "[[" 
> but rather to  "<-"  which momentarily turns off auto-printing.

Yes, not being related to "[[" is exactly why it is surprising.

I would expect vv[[f(x)]] to print regardless of f's auto-printing
behavior.

f1 <- function(x) x
f2 <- function(x) return(invisible(x))
a <- list(b=5)
a[[f1("a")]]
a[[f2("a")]]

> Similar things happen in many similar circumstances.

Here's a similar thing:

> v <- 1:5
> v
[1] 1 2 3 4 5
> v[mustBeDocumentedSomewhere=3]
[1] 3

And this can be confusing if one thinks that subsetting is really a
function and behaves like other R functions w.r.t. to treatment of
named arguments:

> m <- matrix(1:4, nrow=2)
> m
     [,1] [,2]
[1,]    1    3
[2,]    2    4
> m[j=2]
[1] 2




More information about the R-devel mailing list