Search code examples
rtidyrreshape2meltdcast

Reshaping multiple long columns into wide column format in R


My sample dataset has multiple columns that I want to convert into wide format. I have tried using the dcast function, but I get error. Below is my sample dataset:

df2 = data.frame(emp_id = c(rep(1,2), rep(2,4),rep(3,3)), 
                 Name = c(rep("John",2), rep("Kellie",4), rep("Steve",3)),
                 Year = c("2018","2019","2018","2018","2019","2019","2018","2019","2019"),
                 Type = c(rep("Salaried",2), rep("Hourly", 2), rep("Salaried",2),"Hourly",rep("Salaried",2)),
                 Dept = c("Sales","IT","Sales","Sales", rep("IT",3),rep("Sales",2)),
                 Salary = c(100,1000,95,95,1500,1500,90,1200,1200))

I'm expecting my output to look like:

enter image description here


Solution

  • One option is the function pivot_wider() from the tidyr package:

    df.wide <- tidyr::pivot_wider(df2,
                                  names_from = c("Type", "Dept", "Year"),
                                  values_from = "Salary",
                                  values_fn = {mean})
    

    This should get you the desired result.