Skip to content

pivot_wider() can result in >0 rows if given a 0 row data frame #1252

@DavisVaughan

Description

@DavisVaughan

I think this is highly related to #1250, and can be fixed after we merge that

library(tidyr)

spec <- tibble(.name = "name", .value = "value", x = 1L)

df <- tibble(value = 1L, x = 2L)
pivot_wider_spec(df, spec)
#> # A tibble: 1 × 1
#>    name
#>   <int>
#> 1    NA

# this is wrong
df <- tibble(value = integer(), x = integer())
pivot_wider_spec(df, spec)
#> # A tibble: 1 × 1
#>    name
#>   <int>
#> 1    NA

I think that has to do with this "hack" (?) here

tidyr/R/pivot-wide.R

Lines 234 to 239 in 0bd56a7

if (ncol(df_rows) == 0) {
rows <- tibble(.rows = 1)
nrow <- 1L
# use `nrow(data)` here because data.table returns zero rows if no
# column is selected
row_id <- rep(1L, nrow(data))

which is necessary for the above example to even run when df has zero rows, but that is due to #1250, so if we fix that then we should be able to remove the hack and get the correct answer

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviorpivoting ♻️pivot rectangular data to different "shapes"

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions