I have solved a problem using the dcast function from reshape library. However, I don't usually work with that library and generally I prefer working with dplyr.
Here's the data example:
segment<- c('seg1', 'seg1', 'seg2', 'seg2', 'seg1', 'seg2', 'seg3', 'seg3', 'seg2', 'seg3')
Company<- c('c1', 'c2', 'c3', 'c4', 'c5', 'c2', 'c1', 'c3', 'c4', 'c5' )
var.1<- c(100, 20, 30, 50, 40, 40, 20, 30, 50, 40)
var.2<- c(200, 30, 30, 70, 30, 140, 100, 30, 90, 10)
var.3<- c(50, 50, 40, 20, 30, 40, 50, 40, 20, 30)
var.4<- c(60, 50, 35, 53, 42, 20, 100, 20, 30, 50)
df<- data.frame(segment, Company, var.1, var.2, var.3, var.4)
We want to reshape that data frame so the results will be:
new.df<- df %>%
melt(id.vars = c(1:2)) %>%
dcast(`segment` + `variable` ~ `Company`)
I try to achieve this same results using group_by and pivot_longer function instead of melt & dcast but I can't make it work (The only way I could make it work was if I choose 1 of my 4 variables to store in the cells but I want all 4 of them to exist).