This question has a partial answer here but the question is too specific and I'm not able to apply it to my own problem.
I would like to skip a potentially heavy computation of the NA group when using by
.
library(data.table)
DT = data.table(X = sample(10),
Y = sample(10),
g1 = sample(letters[1:2], 10, TRUE),
g2 = sample(letters[1:2], 10, TRUE))
set(DT, 1L, 3L, NA)
set(DT, 1L, 4L, NA)
set(DT, 6L, 3L, NA)
set(DT, 6L, 4L, NA)
DT[, mean(X*Y), by = .(g1,g2)]
Here we can see there are up to 5 groups including the (NA, NA)
group. Considering that (i) the group is useless (ii) the groups can be very big and (iii) the actual computation is more complex than mean(X*Y)
can I skip the group in an efficient way? I mean, without creating a copy of the remaining table. Indeed the following works.
DT2 = data.table:::na.omit.data.table(DT, cols = c("g1", "g2"))
DT2[, mean(X*Y), by = .(g1,g2)]
You can use an if
clause:
DT[, if (!anyNA(.BY)) mean(X*Y), by = .(g1,g2)]
g1 g2 V1
1: b a 25.75000
2: a b 24.00000
3: b b 35.33333
From the ?.BY
help:
.BY
is alist
containing a length 1 vector for each item inby
. This can be useful [...] to branch withif()
depending on the value of a group variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With