Skip to content

Instantly share code, notes, and snippets.

@msummersgill
Last active March 14, 2019 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msummersgill/0972314d757324dc5d70968256bd62ea to your computer and use it in GitHub Desktop.
Save msummersgill/0972314d757324dc5d70968256bd62ea to your computer and use it in GitHub Desktop.
.BY experimenting
library(data.table)
dta <- data.table(gr = LETTERS[1:3],
a = 1,
b = 1)
add <- function(x, y, group) if(group == "B") x + y else x - y
dta[,.BY, by = .(gr)]
# gr BY
# 1: A A
# 2: B B
# 3: C C
dta[,str(.BY), by = .(gr)]
# List of 1
# $ gr: chr "A"
# List of 1
# $ gr: chr "B"
# List of 1
# $ gr: chr "C"
# Empty data.table (0 rows) of 1 col: gr
dta[,str(.BY$gr), by = .(gr)]
# chr "A"
# chr "B"
# chr "C"
# Empty data.table (0 rows) of 1 col: gr
dta[, newcol := add(a, b, .BY), by = .(gr)]
dta
# gr a b newcol
# 1: A 1 1 0
# 2: B 1 1 2
# 3: C 1 1 0
## Another Example:
set.seed(1)
DT <- data.table(x = rep(LETTERS[1:3],4),
y = rep(letters[1:2],6),
z = rnorm(12,10))
DT[, .(x_GroupValue = .BY$x,
y_GroupValue = .BY$y,
RowCount = .N,
z_Average = mean(z)), by = .(x,y)]
# x y x_GroupValue y_GroupValue RowCount z_Average
# 1: A a A a 2 9.930488
# 2: B b B b 2 10.460984
# 3: C a C a 2 9.870076
# 4: A b A b 2 10.644946
# 5: B a B a 2 10.920644
# 6: C b C b 2 9.784687
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment