35  Advanced Usage Examples

This is a growing list of slightly more advanced examples using data.table.

library(data.table)
options(datatable.print.class = TRUE)

35.1 Count by group using .N

Example: Count penguins by island:

peng[, .N, by = island]
      island     N
      <fctr> <int>
1: Torgersen    52
2:    Biscoe   168
3:     Dream   124

Example: Count by island and species:

peng[, .N, by = list(island, species)]
      island   species     N
      <fctr>    <fctr> <int>
1: Torgersen    Adelie    52
2:    Biscoe    Adelie    44
3:     Dream    Adelie    56
4:    Biscoe    Gentoo   124
5:     Dream Chinstrap    68

35.2 Index within groups using .I

For example, get index for min or max within each group, where index refers to the entire data.table.

Look at the documentation for .I

ir <- as.data.table(iris)
ir[, .I[which.max(Petal.Width)], by = Species]
      Species    V1
       <fctr> <int>
1:     setosa    44
2: versicolor    71
3:  virginica   101

Use that to get the case with max Petal.Width from each Species

ir[, ir[, .I[which.max(Petal.Width)], by = Species][[2]]]
[1]  44  71 101

35.3 See also