Skip to content

slice() behaves differently to head() on nested tibbles vs. unnested tibbles. #1553

Closed
@cynthiahqy

Description

@cynthiahqy

slice() should return the same as head() when extracting the first row of a table. For normal tibbles it does so, but when working with nested tibbles, only head(1) works as expected (returning the first row), while slice(1) returns all rows, and slice(2) returns no rows.

I've included a reprex of the unexpected behaviour with dplyr functions, but I suspect the issue is to do with the behaviour of nested tibbles so I've raised the issue here.

library(dplyr, quietly = TRUE, warn.conflicts = FALSE)
# Normal tibble
## these two are equivalent
identical(head(mtcars, 1), slice(mtcars, 1))
#> [1] TRUE

# Nested Tibble
## gets the first row as expected
mtcars |> nest_by(cyl) |> head(1)
#> # A tibble: 1 × 2
#> # Rowwise:  cyl
#>     cyl                data
#>   <dbl> <list<tibble[,10]>>
#> 1     4           [11 × 10]
## returns all rows unexpectedly
mtcars |> nest_by(cyl) |> slice(1)
#> # A tibble: 3 × 2
#> # Rowwise:  cyl
#>     cyl                data
#>   <dbl> <list<tibble[,10]>>
#> 1     4           [11 × 10]
#> 2     6            [7 × 10]
#> 3     8           [14 × 10]
## returns no rows unexpectedly
mtcars |> nest_by(cyl) |> slice(2)
#> # A tibble: 0 × 2
#> # Rowwise:  cyl
#> # ℹ 2 variables: cyl <dbl>, data <list<tibble[,10]>>

Created on 2024-06-12 with reprex v2.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions