Skip to content

pivot_wider does not work well with data.table #1066

@ColeMiller1

Description

@ColeMiller1

Per this StackOverflow Question, it appears that there can be errors when data.table is loaded and data.table methods are dispatched on data.table objects (i.e., [.data.frame vs. [.data.table.

library(data.table)
library(tidyr)
library(dplyr)

df <- data.frame(names=letters[1:3],values=1:3)
df %>% pivot_wider(names_from=names,values_from=values)
#> # A tibble: 1 x 3
#>       a     b     c
#>   <int> <int> <int>
#> 1     1     2     3

dt <- data.table(names1=letters[1:3],values1=1:3)
pivot_wider(dt, names_from=names1,values_from=values1)
#> Error in data.frame(row = row_id, col = col_id): arguments imply differing number of rows: 0, 3

This is the traceback:

5: stop(gettextf("arguments imply differing number of rows: %s",
paste(unique(nrows), collapse = ", ")), domain = NA)
4: data.frame(row = row_id, col = col_id)
3: pivot_wider_spec(data, spec, !!id_cols, names_repair = names_repair,
values_fill = values_fill, values_fn = values_fn)
2: pivot_wider.data.frame(dt, names_from = names1, values_from = values1)
1: pivot_wider(dt, names_from = names1, values_from = values1)

I believe this is the problem:

df_rows <- data[key_vars]

To make it agnostic between data.table and data.frame methods, this should work:

df_rows <- data[, key_vars, drop = FALSE]

As is, dt[cols] would be equivalent to df[cols, ]. I can make a PR if you'd like.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurea feature request or enhancementpivoting ♻️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