Reshaping data is similar to creating a contingency table, which enables the user to aggregate data of specific values. The reshape2
package is designed for this specific purpose. Here, we introduce how to use the reshape2
package to transform our dataset from long to wide format with the dcast
function. We also cover how to transform it from wide format back to long format with the melt
function.
Refer to the Merging data recipe and merge employees
and salaries
into employees_salary
.
Perform the following steps to reshape data:
First, we can use the
dcast
function to transform data from long to wide:> wide_salaries <- dcast(salaries, emp_no ~ year(ymd(from_date)), value.var="salary") > wide_salaries[1:3, 1:7] emp_no 1985 1986 1987 1988 1989 1990 1 10001 NA 60117 62102 66074 66596 66961 2 10002 NA NA NA NA NA NA 3 10003 NA NA NA NA NA NA
We can also transform the data by keeping
emp_no
and the formatted...