Home > Blockchain >  Pivot dataframe to switch columns and rows
Pivot dataframe to switch columns and rows

Time:10-24

I wish to use the pivotlonger function on my df to switch some of the columns but am unable to switch the correct columns rows. The original df is below;

Series Name                Country        1997        1998        1999        2000        2001        2002        2003        2004        2005        2006
1  GDP (current US$)                  Spain    5.90E 11    6.19E 11    6.35E 11    5.98E 11    6.28E 11    7.09E 11    9.07E 11    1.07E 12    1.15E 12    1.26E 12
2  GDP (current US$)                 France    1.45E 12    1.50E 12    1.49E 12    1.37E 12    1.38E 12    1.50E 12    1.84E 12    2.12E 12    2.20E 12    2.32E 12
3  GDP (current US$)                 Monaco  2840175545  2934498443  2906093757  2647885849  2718868306  2968987019  3601321065  4137913500  4203084194  4582988333
4  GDP (current US$)                  Italy    1.24E 12    1.27E 12    1.25E 12    1.15E 12    1.17E 12    1.28E 12    1.58E 12    1.81E 12    1.86E 12    1.95E 12
5  GDP (current US$)                Croatia 24091170703 25792876644 23677307509. 21839780971 23273640257 27074550258 34985749883 41958833541 45780237257 50860788253
6  GDP (current US$) Bosnia and Herzegovina  3671816504  4116699437  4685733115  5567405605  5800774707  6728771319  8498560877 10157553968 11222953329 12864610865

I have been able to use pivotlonger to get the df below but i want to get a df with countries as columns names rather than rows. See below df for example

`Series Name`     Country year  value   
   <chr>             <chr>   <chr> <chr>   
 1 GDP (current US$) Spain   1997  5.90E 11
 2 GDP (current US$) Spain   1998  6.19E 11
 3 GDP (current US$) Spain   1999  6.35E 11
 4 GDP (current US$) Spain   2000  5.98E 11
 5 GDP (current US$) Spain   2001  6.28E 11
 6 GDP (current US$) Spain   2002  7.09E 11

looking for something like this;

columns = year spain france monaco italy croatia Bosnia

rows = 1997 1998 1999

CodePudding user response:

pivot_wider(
 df,
 id_cols = c(`Series Name`, year),
 names_from = Country,
 values_from = value
)
  • Related