Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I introduce dcast into data.table chain without using piping?

Tags:

r

data.table

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

like image 212
Grec001 Avatar asked Nov 05 '25 06:11

Grec001


1 Answers

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
like image 140
sindri_baldur Avatar answered Nov 06 '25 20:11

sindri_baldur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!