0

I have a data frame in the wide format as shown below

site    Mean VV 2019    Mean Lst 2019   Mean Vv 2020    Mean Lst 2020   Mean VV 2021    Mean Lst 2021
1       -2              -4              -6.7            -10             -1.67           -24
2       -11             -19             -20             -8              -13             -5

I want to reshape in to longer format as shown below

site    Mean VV Mean LST    Year
1       -2      -4          2019
1       -6.7    -10         2020
1       -1.67   -24         2021
2       -8      -16         2019
2       -5      -12         2020
2       -18     -20         2021

I have used pivot_longer from the tidyr package but it is not producing the desired result. I need year-wise data in the row. I know its a very simple task but righ now I am stucked with this and I will appreciate any help.

gis.rajan
  • 517
  • 3
  • 20
  • 1
    `tidyr::pivot_longer(quux, -site, names_pattern="(.*) ([0-9]+)$", names_to=c(".value", "Year"))` – r2evans Apr 24 '23 at 01:55
  • see https://stackoverflow.com/q/2185252/3358272, https://stackoverflow.com/q/68058000/3358272 (names_pattern) – r2evans Apr 24 '23 at 02:00
  • it's working with the example I provided above, in the original dataset there are more columns so I am trying to run the above code with my original data frame. – gis.rajan Apr 24 '23 at 02:17
  • Okay, will you provide context? "More columns" could be "more columns that should be pivoted", and it might also be "more columns that should not be pivoted". The former can be murky depending on their names, but the latter is clear, add them to the first argument. When in doubt, [read the help page](https://tidyr.tidyverse.org/reference/pivot_longer.html) for which arguments do what. – r2evans Apr 24 '23 at 11:57

0 Answers0