Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to benefit from `.BY` in data.table?

Tags:

r

data.table

This is the explanation in manual of .BY

.BY is a list containing a length 1 vector for each item in by. This can be useful when by is not known in advance. The by variables are also available to j directly by name; useful for example for titles of graphs if j is a plot command, or to branch with if() depending on the value of a group variable.

It says "useful for example for titles of graphs if j is a plot command, or to branch with if() depending on the value of a group variable."

But still, I'm not sure when to use.how to benefit from this .BY?

Could you give one example? Thanks a lot!

like image 740
Bigchao Avatar asked Mar 19 '14 15:03

Bigchao


1 Answers

Here is a simple example. We are using the .BY variable to show which group the plot belongs to. Note that you can also do it without using .BY, by replacing it with gear[1], which will be equivalent.

library(data.table)
mtcars_dt = data.table(mtcars)
mtcars_dt[,
  plot(wt, mpg, main = paste('Gears: ', .BY)),
  gear
]
like image 55
Ramnath Avatar answered Oct 20 '22 20:10

Ramnath