R Grouping data.table by Multiple Variables (Example Code)
In this article you’ll learn how to group data tables in R.
Preparing the Example
install.packages("data.table") # Install & load data.table package library("data.table") |
install.packages("data.table") # Install & load data.table package library("data.table")
my_table <- data.table(ID1 = rep(c("X", "Y", "Z"), each = 6), # Constructing example data.table ID2 = c("foo", "bar"), value = 1:18) my_table # Showing data.table in RStudio # ID1 ID2 value # 1: X foo 1 # 2: X bar 2 # 3: X foo 3 # 4: X bar 4 # 5: X foo 5 # 6: X bar 6 # 7: Y foo 7 # 8: Y bar 8 # 9: Y foo 9 # 10: Y bar 10 # 11: Y foo 11 # 12: Y bar 12 # 13: Z foo 13 # 14: Z bar 14 # 15: Z foo 15 # 16: Z bar 16 # 17: Z foo 17 # 18: Z bar 18 |
my_table <- data.table(ID1 = rep(c("X", "Y", "Z"), each = 6), # Constructing example data.table ID2 = c("foo", "bar"), value = 1:18) my_table # Showing data.table in RStudio # ID1 ID2 value # 1: X foo 1 # 2: X bar 2 # 3: X foo 3 # 4: X bar 4 # 5: X foo 5 # 6: X bar 6 # 7: Y foo 7 # 8: Y bar 8 # 9: Y foo 9 # 10: Y bar 10 # 11: Y foo 11 # 12: Y bar 12 # 13: Z foo 13 # 14: Z bar 14 # 15: Z foo 15 # 16: Z bar 16 # 17: Z foo 17 # 18: Z bar 18
Example: Grouping data.table Based On Multiple Variables
my_table[ , sum:=sum(value), by = list(ID1, ID2)] # Grouping data.table my_table # Showing updated data.table in RStudio # ID1 ID2 value sum # 1: X foo 1 9 # 2: X bar 2 12 # 3: X foo 3 9 # 4: X bar 4 12 # 5: X foo 5 9 # 6: X bar 6 12 # 7: Y foo 7 27 # 8: Y bar 8 30 # 9: Y foo 9 27 # 10: Y bar 10 30 # 11: Y foo 11 27 # 12: Y bar 12 30 # 13: Z foo 13 45 # 14: Z bar 14 48 # 15: Z foo 15 45 # 16: Z bar 16 48 # 17: Z foo 17 45 # 18: Z bar 18 48 |
my_table[ , sum:=sum(value), by = list(ID1, ID2)] # Grouping data.table my_table # Showing updated data.table in RStudio # ID1 ID2 value sum # 1: X foo 1 9 # 2: X bar 2 12 # 3: X foo 3 9 # 4: X bar 4 12 # 5: X foo 5 9 # 6: X bar 6 12 # 7: Y foo 7 27 # 8: Y bar 8 30 # 9: Y foo 9 27 # 10: Y bar 10 30 # 11: Y foo 11 27 # 12: Y bar 12 30 # 13: Z foo 13 45 # 14: Z bar 14 48 # 15: Z foo 15 45 # 16: Z bar 16 48 # 17: Z foo 17 45 # 18: Z bar 18 48
Further Resources & Related Tutorials
Here, you can find some additional resources on topics such as variables, groups, and extracting data.