“[” and “[[” with the apply() functions

[ and [[ are a little bit faster (~15%) in the case below:
prefix <- sample(LETTERS, size=100, replace=TRUE)
paste(prefix, abs(100 * rnorm(100)), sep="-")
library(rbenchmark)
benchmark(sapply(strsplit(id, "-"), function(a) a[1]), sapply(strsplit(id, "-"), "[", 1), order="elapsed", replications=100)

The stupidest thing...

Did you know you can use "[" and "[[" as function names for subsetting with calls to the apply-type functions?

For example, suppose you have a bunch of identifier strings like "ZYY-43S-CWA3" and you want to pull off the bit before the first hyphen ("ZYY" in this case). (For code to create random IDs like that, see the end of this post.)

Suppose the IDs are in a vector of character strings, id.

If I wanted to grab the bit before the first hyphen, I would typically use strsplit and then sapply with function(a) a[1], as so:

But in place of function(a) a[1], you can use "[", 1, as follows:

I think that’s kind of cute. You can use "[[" the same way, if you’re working with lists.

Here’s some code to create random IDs of this form, to test out the above:

View original post

Advertisements

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