How to create a table that makes individual entries for grouped values in R
Clash Royale CLAN TAG#URR8PPP
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
1 Answer
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
result[order(result$Company), ]
Thanks for this. Is there any way to do it in Base R?
– bbbrrr
Aug 8 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 stackoverflow.com/questions/2894775/… some of which are in base R. You can sort it as @RobJan suggested in base R.
– Kerry Jackson
Aug 8 at 18:46
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
And to sort by Company
result[order(result$Company), ]
– RobJan
Aug 8 at 18:29