reshape

Excellent worked example here!

# example data frame: Three measures on each person: Wide format
df = data.frame(
    rbind(c("A", 1, 2, 3),
         c("B", 4, 5, 6),
         c("C", 7, 8, 9)
    )
)
 
names(df)=c("ID", "T0", "T1", "T2")            
df

From wide to long

Example using reshape()

idvar = the column that gives the ID for that row; varying: the list of things to make rows from; v.names: label for the new column in long format

reshape(df, idvar="ID", varying=c("T0","T1","T2"), direction="long", v.names="Time")

Example using melt()

melt(df,id.vars="ID")
  ID variable value
1  A       T0     1
2  B       T0     4
3  C       T0     7
4  A       T1     2
5  B       T1     5
6  C       T1     8
7  A       T2     3
8  B       T2     6
9  C       T2     9

df = data.frame(
rbind(c("A", 1, 2, 3),
c("B", 4, 5, 6),
c("C", 7, 8, 9) )
)
names(df)=c("ID", "T0", "T1", "T2"); df

reshape(df, idvar="ID", varying=c("T0","T1","T2"), direction="long", v.names="Time")

melt(df,id.vars="ID")

recast(smiths, variable ~ subject, id.var="subject")

[[pre]]
variable John Smith Mary Smith
1 time 1.00 1.00
2 age 33.00 NA
3 weight 90.00 NA
4 height 1.87 1.54
[[/pre]]

dataset <- data.frame(var1 = rep(c("a","b","c","d","e","f"), each = 4),
var2 = rep(c("level1","level1","level2","level2"), 6),
var3 = rep(c("h","m"), 12), meas = rep(1:12)
)

dataset$meas[5]=NA

  1. simply pivot table

cast(dataset, var1 ~ var2 + var3, value="meas")
cast(dataset, var1 ~ var2, mean, value="meas")
cast(dataset, var1 ~ var2, mean, na.rm=T, value="meas")

  1. aggregate

ddply(dataset, .(var1, var2), summarise, mean = mean(meas))
ddply(dataset, .(var1), summarise, mean = mean(meas, na.rm=T))

Suggestion

acast()
dcast()

cast_df()
cast_ar()

  1. better yet, just one word, with a parameter, which defaults to the common request (df)

cast(, out="df")

cast means nothing to people, melt even less

instead of "melt" reshape2long()
instead of "cast" reshape2wide()