0

Let us say I have a data frame as follows:

data <- data.frame("Company" = c("X", "Y"),
                   "Chocolate" = c(1, 2),
                   "Vanilla" = c(2 ,1))
data

  Company Chocolate Vanilla
1       X         1       2
2       Y         2       1

How do I reshape this data.frame into the format below:

Company    Type
  X        "Chocolate"
  X        "Vanilla"
  X        "Vanilla"
  Y        "Chocolate"
  Y        "Chocolate"
  Y        "Vanilla"

I am attempting to make an empty data frame then somehow using a "for" loop, but I struggle to understand how to make it work

divibisan
  • 11,659
  • 11
  • 40
  • 58
bbbrrr
  • 3
  • 1

1 Answers1

1

If you are open to using some packages, you can

library(dplyr)
library(tidyr)
library(splitstackshape)

data %>% 
  gather(Type, freq, -Company) %>% # Change the structure to have the types in a column for type
  expandRows("freq") %>% # Repeat each row how many times indicated
  arrange(Company) # Sort by company

  Company      Type
1       X Chocolate
2       X   Vanilla
3       X   Vanilla
4       Y Chocolate
5       Y Chocolate
6       Y   Vanilla
Kerry Jackson
  • 1,821
  • 12
  • 20
  • And to sort by _Company_ `result[order(result$Company), ]` – RobJan Aug 08 '18 at 18:29
  • Thanks for this. Is there any way to do it in Base R? – bbbrrr Aug 08 '18 at 18:42
  • There probably are ways to do this in base R, but I am not sure exactly how to do all the steps. You can repeat the rows using the answers from https://stackoverflow.com/questions/2894775/replicate-each-row-of-data-frame-and-specify-the-number-of-replications-for-each some of which are in base R. You can sort it as @RobJan suggested in base R. – Kerry Jackson Aug 08 '18 at 18:46