bbbrrr
bbbrrr

Reputation: 3

How to create a table that makes individual entries for grouped values in R

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

Upvotes: 0

Views: 42

Answers (1)

Kerry Jackson
Kerry Jackson

Reputation: 1871

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

Upvotes: 1

Related Questions