The base reshape
function works perfectly fine:
df <- data.frame(
year = c(rep(2000, 12), rep(2001, 12)),
month = rep(1:12, 2),
values = rnorm(24)
)
df_wide <- reshape(df, idvar="year", timevar="month", v.names="values", direction="wide", sep="_")
df_wide
Where
idvar
is the column of classes that separates rowstimevar
is the column of classes to cast widev.names
is the column containing numeric valuesdirection
specifies wide or long formatsep
argument is the separator used in between timevar
class names and v.names
in the output data.frame
. If no idvar
exists, create one before using the reshape()
function:
df$id <- c(rep("year1", 12), rep("year2", 12))
df_wide <- reshape(df, idvar="id", timevar="month", v.names="values", direction="wide", sep="_")
df_wide
Just remember that idvar
is required! The timevar
and v.names
part is easy. The output of this function is more predictable than some of the others, as everything is explicitly defined.