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

Time:06-21

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?

CodePudding user response:

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

CodePudding user response:

in Base R:

unstack(df, Sales_in_Dollars~Item_Number)

  X50 X60 X70
1  10  20  35
2  15  30  45

CodePudding user response:

With data.table:

data.table::dcast(as.data.table(df),
                  rowid(`Item.Number`) ~ `Item.Number`,
                  value.var = "Sales.in.Dollars")[, -1]

Output

      50    60    70
   <int> <int> <int>
1:    10    20    35
2:    15    30    45

CodePudding user response:

Another possible solution, based on tidyverse:

library(tidyverse)

df %>% 
  pivot_wider(names_from = item, values_from = sales, values_fn = list) %>% 
  unnest(everything())

#> # A tibble: 2 x 3
#>    `50`  `60`  `70`
#>   <int> <int> <int>
#> 1    10    20    35
#> 2    15    30    45
  • Related