[R] Partial matching when using $ ? Feature or bug?

Sarah Goslee sarah.goslee at gmail.com
Fri Mar 16 14:54:13 CET 2012


Hi Rainer,

On Fri, Mar 16, 2012 at 9:45 AM, Rainer M Krug <r.m.krug at gmail.com> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi
>
> I have the following code:
>
>  x <- data.frame(x1=1, x2=2, y1=3)
>  x$y
> [1] 3
>  x$x
> NULL

>
> I was surprised (and definitely irritated?) when I realised that partial matching also works for
> the $. Is this intended?

This is documented behavior, which by definition makes it a feature, right?

     Both ‘[[’ and ‘$’ select a single element of the list.  The main
     difference is that ‘$’ does not allow computed indices, whereas
     ‘[[’ does.  ‘x$name’ is equivalent to ‘x[["name", exact =
     FALSE]]’.  Also, the partial matching behavior of ‘[[’ can be
     controlled using the ‘exact’ argument.

It's also a really good reason to use [[ in functions or anywhere
there might be a chance of confusion.

Sarah

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list