Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I reshape my data so that rows are columns in R?

I have a dataset that contains the following values

       Item Number  Sales in Dollars
1          50           10                   
2          50           15
3          60           20
4          60           30
5          70           35
6          70           45

I would like to reshape the data such that the result would be

       50  60 70
1      10  20 35                        
2      15  30 45

How could I go about achieving this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We could use pivot_wider:
The trick is to group_by and create an id in the the group to get this output, otherwise you will get a list with NAs

library(dplyr)
library(tidyr)

df %>% 
  group_by(ItemNumber) %>% 
  mutate(id = row_number()) %>% 
  pivot_wider(names_from=ItemNumber, values_from = SalesinDollars) %>% 
  select(-id)
   `50`  `60`  `70`
  <int> <int> <int>
1    10    20    35
2    15    30    45
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading