如何在不使用管道的情况下将dcast引入data.table链中?

时间:2019-03-11 09:25:51

标签: r data.table

data.table使用链规则是优雅而直观的。一切都像一台机器一样排列。但是有时我们必须引入一些操作,例如dcast或melt。如何将所有操作集成到[]中?我承认,仅仅是因为它更加优美。

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)]

我可以删除%>%并集成到[]中吗? 谢谢

1 个答案:

答案 0 :(得分:3)

为此目的如何使用.SD

DT[, .N, by = .(B, C)
   ][, dcast(.SD, B ~ C)
     ][, .N, by = .(NG)]

   NG N
1: NA 2
2:  3 2