data.table is graceful and intuitive with the chains rule. Everything is just lined up like a machine. But sometimes we have to introduce some operation like dcast or melt.
How can I integrate all operation into the []? Simply because it's more graceful, I admit.
DT <- data.table(A = rep(letters[1:3],4), B = rep(1:4,3), C = rep(c("OK", "NG"),6))
DT.1 <- DT[,.N, by = .(B,C)] %>% dcast(B~C)
DT.2 <- DT.1[,.N, by = .(NG)]
# NG N
#1: NA 2
#2: 3 2
#same
DT <- data.table(A = rep(letters[1:3],4), B = rep(1:4,3), C = rep(c("OK", "NG"),6))[,.N, by = .(B, C)] %>%
dcast(B~C) %>% .[,.N, by =.(NG)]
Can I remove the %>% and integrate into the []?
Thanks
What about using .SD to this end:
DT[, .N, by = .(B, C)
][, dcast(.SD, B ~ C)
][, .N, by = .(NG)]
NG N
1: NA 2
2: 3 2
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