Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

counting a specific variable does not take grouping variables into account #97

Closed
hlynurhallgrims opened this issue Aug 22, 2019 · 1 comment

Comments

@hlynurhallgrims
Copy link

When doing a count on a grouped data.table with dtplyr, only the variable you are counting by is passed to keyby=, but not the current grouping variables (as is the "regular" behaviour in dplyr).

suppressPackageStartupMessages(library(dplyr))

flight_dt <- nycflights13::flights %>% 
  dtplyr::lazy_dt() 

# This is how it works on a data.table
flight_dt %>%   
  group_by(year, month) %>% 
  count(tailnum)
#> Source: local data table [?? x 2]
#> Call:   `_DT1`[, .(n = .N), keyby = .(tailnum)]
#> 
#>   tailnum     n
#>   <chr>   <int>
#> 1 <NA>     2512
#> 2 D942DN      4
#> 3 N0EGMQ    371
#> 4 N10156    153
#> 5 N102UW     48
#> 6 N103US     46
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

# This works and gives the expected output of the previous code
flight_dt %>% 
  group_by(year, month, tailnum) %>% 
  count()
#> Source: local data table [?? x 4]
#> Call:   `_DT1`[, .(n = .N), keyby = .(year, month, tailnum)]
#> 
#>    year month tailnum     n
#>   <int> <int> <chr>   <int>
#> 1  2013     1 <NA>      155
#> 2  2013     1 N0EGMQ     41
#> 3  2013     1 N10156     28
#> 4  2013     1 N102UW      1
#> 5  2013     1 N103US      4
#> 6  2013     1 N104UW      2
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

Created on 2019-08-22 by the reprex package (v0.2.0).


p.s. this package is amazing 😍

@hadley
Copy link
Member

hadley commented Aug 22, 2019

Slightly simpler reprex:

library(dtplyr)
suppressPackageStartupMessages(library(dplyr))

mtcars %>%  
  group_by(vs) %>% 
  count(am)
#> # A tibble: 4 x 3
#> # Groups:   vs [2]
#>      vs    am     n
#>   <dbl> <dbl> <int>
#> 1     0     0    12
#> 2     0     1     6
#> 3     1     0     7
#> 4     1     1     7

mtcars %>%  
  lazy_dt() %>% 
  group_by(vs) %>% 
  count(am)
#> Source: local data table [?? x 2]
#> Call:   `_DT1`[, .(n = .N), keyby = .(am)]
#> 
#>      am     n
#>   <dbl> <int>
#> 1     0    19
#> 2     1    13
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

Created on 2019-08-22 by the reprex package (v0.3.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants