How to build a pipeline from data.table to magrittr and return to data.table

I would like to combine .table pipelining with magrittr pipelining. I can go from data.table to%>%, but I can't figure out how to get back to the [] [] pipeline of the data.table style.

Here is an example:

> tbl = data.table(grp=c(1,1,1,2,2,2,3,3,3,4,4), y=rnorm(11)) > tbl grp y 1: 1 0.08150 2: 1 1.51330 3: 1 -0.26154 4: 2 -0.12746 5: 2 0.10747 6: 2 0.16502 7: 3 0.54139 8: 3 -0.04194 9: 3 0.02373 10: 4 2.00756 11: 4 1.05523 > tbl[, .(.N, mean(y)), by=grp][order(-N)] %>% head(n=3) %>% .[, N := NULL] grp V2 1: 1 0.44442 2: 2 0.04834 3: 3 0.17439 > tbl[, .(.N, mean(y)), by=grp][order(-N)] %>% head(n=3) %>% .[, N := NULL][, plot(grp, V2)] Error in `[.data.table`(., .[, `:=`(N, NULL)], , plot(grp, V2)) : 'by' or 'keyby' is supplied but not j Calls: %>% ... freduce -> withVisible -> <Anonymous> -> [ -> [.data.table > 

How to return to [] [] after%>%?

I know that this particular example can be completely rewritten with [] and without%>%, but I am not interested in this every time. I would like to be able to write [] []%>% [] [] patterns.

+7
r data.table magrittr
source share
3 answers

You can do

  `tbl %>% filter(y>0) %>% data.table()` 

to convert the result of the pipeline to data.table , for example, to beautifully print the results - using data.table . But unfortunately, you cannot do something like

  `tbl %>% filter(y>0) %>% data.table() [, mean(y), by=group] 

I wonder if this functionality has been added to future versions of data.table - perhaps through the new syntax (to overcome the restriction of the order of priority, since "[" is executed to "<").

+2
source share

Both of the previous answers do not take into account your ability to indicate, to some extent, priority. You can do this by increasing the priority of the %>% code by including it in {} s:

 x <- data.frame(a=1:5, b=6:10) {x %>% subset(a<4) %>% data.table()}[, mean(b)] 

Not really, but it works:

 > {x %>% subset(a<4) %>% data.table()} [, mean(b)] [1] 7 
+1
source share

You can not. [ has a higher priority than %any% , so it will always be ranked first.

0
source share

All Articles