7

I recently noticed in some old code that I had been including extra square brackets when subsetting a data.table and performing a function repeatedly (in my case, calculating correlation matrices). So,

# Slow way
rcorr(DT[subgroup][, !'Group', with=F])

# Faster way
rcorr(DT[subgroup, !'Group', with=F])

(The difference being after subgroup). Just out of curiosity, why does this occur? With the extra brackets, does data.table have to perform some extra computations?

2
  • I think this answer should be of some help, in addition to Richard's nice answer.
    – Arun
    Jul 24, 2015 at 6:31
  • Absolutely! That was an extremely helpful answer, thanks! Jul 24, 2015 at 7:40

1 Answer 1

6

Here's a simple interpretation:

# Slow way
rcorr(DT[subgroup][, !'Group'])

The second set of brackets is a second operation on DT, meaning that DT[subgroup] creates a new data table from DT, and then [, !'Group'] operates on that data table, creating another new data table. Hence the decline in speed.

# Faster way
rcorr(DT[subgroup, !'Group'])

This way operates only on DT, all in one go.

2
  • Thanks! I figured something like that was going on. Jul 24, 2015 at 0:11
  • 1
    @Chris, it works on the same premise that [ would in base R, if that helps Jul 24, 2015 at 0:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.