x[[c(5,3)]]

An R tip:
Did you know that x[[c(5,3)]] is the same as x[[5]][[3]]?

I should make more thorough use of this.

In the help file for [[:

[[ can be applied recursively to lists, so that if the single index i is a vector of length p, alist[[i]] is equivalent to alist[[i1]]...[[ip]] providing all but the final indexing results in a list.

I never knew this; I came across it when playing around (i.e., not paying proper attention) in the back of the room at an R course.

Did you know that [[ had a help file? Type ?"[["

About these ads

Tags: ,

6 Responses to “x[[c(5,3)]]”

  1. Yihui Says:

    I never knew this either! It does not sound like a good idea…

  2. Hansi Says:

    From a readability perspective I’d avoid this. Also x[c(5,3)] will return the 5th and 3rd items in a list. Instead of the 3rd item of the 5th item. Seems like a potential way of making mistakes

    • Karl Broman Says:

      Good points.

      It would be useful for programming with arbitrary levels of nesting, though…you don’t need to know in advance how many sets of double-brackets to use.

  3. Ken Butler Says:

    This is cool, in a kind of odd way, but in the grand scheme of things I’d say its only benefit is to save some typing.

  4. fer_rabanal Says:

    Reblogged this on Easy ML World and commented:
    I really love this post… ;)

  5. isomorphismes Says:

    This is a weird language, for sure…. Thanks for the tip.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 87 other followers