Skip to content

pivot_longer only returns a subset of data from cols #792

@tdhock

Description

@tdhock

I'm using pivot_longer with names_pattern, and the number of rows returned depends on the names_to/names_pattern arguments. I expected that the number of rows returns should only depend on cols.

For example consider two columns of the iris data. I expected that both of the following would result in 8 rows.

tidyr::pivot_longer(iris[c(1,51),], 1:4, names_to="part", names_pattern="(.*)[.].*")
tidyr::pivot_longer(iris[c(1,51),], 1:4, names_to=c("part", "dim"), names_pattern="(.*)[.](.*)")

However the first one only returns 4 rows (only the Width data, not the Length data).

> tidyr::pivot_longer(iris[c(1,51),], 1:4, names_to="part", names_pattern="(.*)[.].*")
# A tibble: 4 x 3
  Species    part  value
  <fct>      <chr> <dbl>
1 setosa     Sepal   3.5
2 setosa     Petal   0.2
3 versicolor Sepal   3.2
4 versicolor Petal   1.4
> tidyr::pivot_longer(iris[c(1,51),], 1:4, names_to=c("part", "dim"), names_pattern="(.*)[.](.*)")
# A tibble: 8 x 4
  Species    part  dim    value
  <fct>      <chr> <chr>  <dbl>
1 setosa     Sepal Length   5.1
2 setosa     Sepal Width    3.5
3 setosa     Petal Length   1.4
4 setosa     Petal Width    0.2
5 versicolor Sepal Length   7  
6 versicolor Sepal Width    3.2
7 versicolor Petal Length   4.7
8 versicolor Petal Width    1.4
> 

I would have expected a warning, something like "you asked to pivot columns 1:4 but we only are returning data from columns 2 and 4"

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

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions