## 7.5 小技巧

### 7.5.1 用{}抑制中间过程输出

dt <- data.table(mtcars)
dt[,{tmp1=mean(mpg); tmp2=mean(abs(mpg-tmp1)); tmp3=round(tmp2, 2)}, by=cyl]
#>    cyl   V1
#> 1:   6 1.19
#> 2:   4 3.83
#> 3:   8 1.79

dt <- data.table(mtcars)
res <- dt[,tmp1:=mean(mpg), by=cyl][,.(tmp2=mean(abs(mpg-tmp1))), by=.(cyl)]
res[,.(round(tmp2,2)),by=.(cyl)][]
#>    cyl   V1
#> 1:   6 1.19
#> 2:   4 3.83
#> 3:   8 1.79

dt[,{tmp1=mean(mpg); tmp2=mean(abs(mpg-tmp1)); tmp3=round(tmp2, 2); list(tmp2=tmp2, tmp3=tmp3)}, by=cyl][]
#>    cyl tmp2 tmp3
#> 1:   6 1.19 1.19
#> 2:   4 3.83 3.83
#> 3:   8 1.79 1.79

dt[,{tmp1=mean(mpg)
tmp2=mean(abs(mpg-tmp1))
tmp3=round(tmp2, 2)
list(tmp2=tmp2, tmp3=tmp3)},
by=cyl][]
#>    cyl tmp2 tmp3
#> 1:   6 1.19 1.19
#> 2:   4 3.83 3.83
#> 3:   8 1.79 1.79

### 7.5.2 使用[]打印data.table

df <- head(mtcars) # doesn't print
(df <- head(mtcars)) # does print
#> # A tibble: 6 x 11
#>     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
#>   <dbl> <int> <dbl> <int> <dbl> <dbl> <dbl> <int> <int> <int> <int>
#> 1  21       6   160   110  3.9   2.62  16.5     0     1     4     4
#> 2  21       6   160   110  3.9   2.88  17.0     0     1     4     4
#> 3  22.8     4   108    93  3.85  2.32  18.6     1     1     4     1
#> 4  21.4     6   258   110  3.08  3.22  19.4     1     0     3     1
#> 5  18.7     8   360   175  3.15  3.44  17.0     0     0     3     2
#> 6  18.1     6   225   105  2.76  3.46  20.2     1     0     3     1
# data.table way of printing after an assignment
dt <- data.table(head(mtcars)) # doesn't print
dt[,hp2wt:=hp/wt][] # does print
#>     mpg cyl disp  hp drat   wt qsec vs am gear carb hp2wt
#> 1: 21.0   6  160 110 3.90 2.62 16.5  0  1    4    4  42.0
#> 2: 21.0   6  160 110 3.90 2.88 17.0  0  1    4    4  38.3
#> 3: 22.8   4  108  93 3.85 2.32 18.6  1  1    4    1  40.1
#> 4: 21.4   6  258 110 3.08 3.21 19.4  1  0    3    1  34.2
#> 5: 18.7   8  360 175 3.15 3.44 17.0  0  0    3    2  50.9
#> 6: 18.1   6  225 105 2.76 3.46 20.2  1  0    3    1  30.3