Is this a bug?
library(data.table)
DT <- as.data.table(mtcars)
# example of something with any zeros
DT[vs==0,length(vs)]
#> [1] 18
DT[.(0),.N,on="vs"]
#> [1] 18
# example of something without any zeros
DT[mpg==0,length(mpg)]
#> [1] 0
DT[.(0),length(vs),on="mpg"]
#> [1] 1
DT[.(0),.N,on="mpg"]
#> [1] 1
DT[mpg==0,.N]
#> [1] 0
# Output of sessionInfo()
sessionInfo()
#> R version 3.6.0 (2019-04-26)
#> Platform: x86_64-apple-darwin15.6.0 (64-bit)
#> Running under: macOS Mojave 10.14.5
#>
#> Matrix products: default
#> BLAS: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib
#>
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> loaded via a namespace (and not attached):
#> [1] compiler_3.6.0 magrittr_1.5 tools_3.6.0 htmltools_0.3.6
#> [5] yaml_2.2.0 Rcpp_1.0.1 stringi_1.4.3 rmarkdown_1.13
#> [9] highr_0.8 knitr_1.23 stringr_1.4.0 xfun_0.8
#> [13] digest_0.6.19 evaluate_0.14
By default, DT[.(0), on = "mpg"] returns a one-row data table with mpg = 0 and all others NA if there's no mpg == 0 in DT, which right-join by definition.
If you want to get 0, you may try DT[.(0),.N,on="mpg",nomatch=0].
already answered by @renkun-ken, closing.
also note that nomatch=NULL instead of nomatch=0 should be preferred.
Most helpful comment
By default,
DT[.(0), on = "mpg"]returns a one-row data table withmpg = 0and all othersNAif there's nompg == 0inDT, which right-join by definition.If you want to get
0, you may tryDT[.(0),.N,on="mpg",nomatch=0].