Search code examples
rlistpivot

pivot_wider command generates a list() instead of a "wider" data.frame in R


I have data.frame with two columns the first shows the value of a year and the second the epoch.

I use the pivot_wider command to create two columns: one with only rainy season values and one with dry season. However, I got as a result an object of type list() with two vector elements, one with the values of the rainy season and the other of the dry season. This object cannot convert to data.frame format with two dry and rainy columns, even using the as.data.frame() command.

dput

df<-structure(list(corr = c(0.74744744694889, 0.74744744694889, -0.74744744694889, 
0.710707994222, -0.672727272727273, -0.627272727272727, 0.721341509883808, 
0.74744744694889, 0.74744744694889, -0.74744744694889, 0.710707994222, 
-0.672727272727273, -0.627272727272727, 0.721341509883808, 0.74744744694889, 
0.74744744694889, -0.74744744694889, 0.706152173746218, -0.690909090909091, 
-0.627272727272727, 0.721341509883808, -0.569861483395246, -0.721861340047052, 
0.609081215121124, 0.74744744694889, 0.74744744694889, -0.74744744694889, 
0.664332608058143, 0.683373071367308, 0.608092810550575, -0.745454545454545, 
0.74744744694889, 0.74744744694889, -0.74744744694889, 0.664332608058143, 
0.683373071367308, 0.608092810550575, -0.745454545454545, -0.836363636363636, 
-0.74744744694889, 0.695967494156149, 0.608092810550575, 0.824603506116551, 
0.74744744694889, 0.74744744694889, -0.556029893992449, -0.682125853438958, 
0.556029893992449, 0.729285774909194), season = c("wet", "wet", 
"wet", "wet", "wet", "wet", "wet", "dry", "dry", "dry", "dry", 
"dry", "dry", "dry", "wet", "wet", "wet", "wet", "wet", "wet", 
"wet", "dry", "dry", "dry", "dry", "dry", "dry", "dry", "dry", 
"dry", "dry", "wet", "wet", "wet", "wet", "wet", "wet", "wet", 
"wet", "wet", "wet", "wet", "wet", "wet", "wet", "dry", "dry", 
"dry", "dry")), row.names = c(NA, -49L), class = "data.frame")

I tryed this:

  df2<-df%>%
    pivot_wider(names_from = season, values_from = corr)

output

enter image description here

I would like to get a dataframe with only two columns: wet and dry and their respective values.


Solution

  • Add an id column and things get easier:

    df %>%
      mutate(id = row_number(), .by = season) %>%
      pivot_wider(names_from = season, values_from = corr, id_cols = id)
    # # A tibble: 28 × 3
    #       id    wet    dry
    #    <int>  <dbl>  <dbl>
    #  1     1  0.747  0.747
    #  2     2  0.747  0.747
    #  3     3 -0.747 -0.747
    #  4     4  0.711  0.711
    #  5     5 -0.673 -0.673
    #  6     6 -0.627 -0.627
    #  7     7  0.721  0.721
    #  8     8  0.747 -0.570
    #  9     9  0.747 -0.722
    # 10    10 -0.747  0.609
    # # … with 18 more rows