Skip to content

accumulate() issues with list output of one row #809

Description

@erictleung

This is an odd "bug" I've encountered. It is not unexpected given the functions used. So I'm both asking if there is a better way to do this or if the functionality should be updated. If this is beyond the scope of purrr, feel free to close.

I wish to accumulate a list of unique values into a cell, but when we accumulate on a single row, it returns a single value. This single value doesn't fit with the other outputs because they are lists. This

library(purrr)
library(dplyr)

running_unique <- function(x, y) { unique(c(x, y)) }

# Example simple function use
running_unique(1, c(1, 12, 3))
#> [1]  1 12  3

# Example using accumulate
accumulate(1:3, running_unique)
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 1 2
#> 
#> [[3]]
#> [1] 1 2 3
accumulate(1, running_unique)
#> [1] 1


df <- tribble(
  ~a, ~b,
  1, 1,
  2, 1,
  2, 2
)
df
#> # A tibble: 3 x 2
#>       a     b
#>   <dbl> <dbl>
#> 1     1     1
#> 2     2     1
#> 3     2     2

df %>%
  group_by(a) %>%
  mutate(accum = accumulate(b, running_unique))
#> Error: Problem with `mutate()` input `accum`.
#> x Input `accum` must return compatible vectors across groups
#> i Input `accum` is `accumulate(b, running_unique)`.
#> i Result type for group 1 (a = 1): <double>.
#> i Result type for group 2 (a = 2): <list>.

Created on 2020-12-04 by the reprex package (v0.3.0)

If we just focus on groups with more than one row, then all is well. Notice that even with one value, it works.

df %>%
  filter(a == 2) %>%
  group_by(a) %>%
  mutate(accum = accumulate(b, running_unique))
#> # A tibble: 2 x 3
#> # Groups:   a [1]
#>       a     b accum    
#>   <dbl> <dbl> <list>   
#> 1     2     1 <dbl [1]>
#> 2     2     2 <dbl [2]>

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions