1

I wanted to use function pivot_longer() and pivot_wider() for iris dataset. This is the code to lengthen the data:

iris_ds <- iris %>% pivot_longer(-Species, names_to = "Measure", values_to = "Value")

In the documentation it says that pivot_wider() is the inverse transformation of pivot_longer(), so I apply the code:

iris_or <- iris_ds %>% pivot_wider(names_from = "Measure", values_from = "Value")

and I get the following table:

    Species    Sepal.Length      Sepal.Width    Petal.Length    Petal.Width
    setosa     <dbl>             <dbl>          <dbl>           <dbl>
    versicolor <dbl>             <dbl>          <dbl>           <dbl>
    virginica  <dbl>             <dbl>          <dbl>           <dbl>

This was answered in the gather() spread() similar question (using a RowId was suggested), the help I want is if the new functions pivot_longer and pivot_wider have a way to manage this to make it transitive. Thank you in advance for your answers.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
Alexis
  • 2,104
  • 2
  • 19
  • 40
  • 4
    You can add `%>% unnest` to the end to get back to the original dimensions – IceCreamToucan Sep 17 '19 at 15:58
  • 1
    Hello @IceCreamToucan, I tried your proposal and it gave me the original dataset, just with a warning, saying cols is now required. Thank you. – Alexis Sep 17 '19 at 16:26

1 Answers1

4

The short answer is no, there's nothing within pivot_* to address this. Might be a good idea to add something in the future to pivot_longer to generate unique rowIDs from within.

As you said, the workaround is to add such row IDs yourself, using tibble's rowid_to_column:

iris %>% rowid_to_column() %>% 
  pivot_longer(-c(Species,rowid), names_to = "Measure", values_to = "Value") %>% 
  pivot_wider(names_from = "Measure", values_from = "Value")

this will bring you back to iris.

iod
  • 7,412
  • 2
  • 17
  • 36