using `dplyr::tally` when column name "n" is present in the dataframe

Viewed 681

I am working with the development version of dplyr and struggling with using dplyr::tally when there is a column name "n" present in the dataframe.

  • dplyr 0.8.5 (CRAN version)

This was not an issue in prior version.

library(tidyverse)

mtcars %>% dplyr::group_by(am) %>% tally(., wt = NULL, name = "n_obs")
#> # A tibble: 2 x 2
#>      am n_obs
#>   <dbl> <int>
#> 1     0    19
#> 2     1    13

df <- dplyr::rename(.data = mtcars, n = wt)

df %>% dplyr::group_by(am) %>% tally(., wt = NULL, name = "n_obs")
#> # A tibble: 2 x 2
#>      am n_obs
#>   <dbl> <int>
#> 1     0    19
#> 2     1    13
  • dplyr 1.0.0 (GitHub version)

But it no longer produces the right output.

library(tidyverse)

mtcars %>% dplyr::group_by(am) %>% tally(., wt = NULL, name = "n_obs")
#> # A tibble: 2 x 2
#>      am n_obs
#> * <dbl> <int>
#> 1     0    19
#> 2     1    13

df <- dplyr::rename(.data = mtcars, n = wt)

df %>% dplyr::group_by(am) %>% tally(., wt = NULL, name = "n_obs")
#> Using `n` as weighting variable
#> # A tibble: 2 x 2
#>      am n_obs
#> * <dbl> <dbl>
#> 1     0  71.6
#> 2     1  31.3

Am I doing something wrong or is this a bug?

1 Answers

Looking at the documentation (as pointed out in the comments), the previous workflow seems to be impossible to recover.

So here is a workaround:

library(tidyverse)

mtcars %>% group_by(am) %>% summarize(n = dplyr::n())
#> # A tibble: 2 x 2
#>      am     n
#> * <dbl> <int>
#> 1     0    19
#> 2     1    13

df <- dplyr::rename(.data = mtcars, n = wt)

df %>% dplyr::group_by(am) %>% summarize(n = dplyr::n())
#> # A tibble: 2 x 2
#>      am     n
#> * <dbl> <int>
#> 1     0    19
#> 2     1    13

Created on 2020-03-24 by the reprex package (v0.3.0)

Related issue on GitHub by someone else: https://github.com/tidyverse/dplyr/issues/5108

Related