It works if you first construct and ID variable
df$id <- 1:nrow(df)
molten <- melt(df, id.var="id")
dcast(molten, id~variable)
If you are already in the molten state, notice from your example, that the rows are sorted properly. You can take advantage of this to construct an ID with rep:
molten$id <- rep(1:(nrow(molten) / 2), 2)
Then the dcast method above will work. Of course, there may be more than two variables that were melted. You can generalize the rep as follows:
molten$id <- rep(1:(nrow(molten) / length(unique(variable))),
length(unique(variable)))
Note that this ID creation relies on two fairly large assumptions:
- The data creator did not sort the data in a manner that would ruin the original order.
- Any missing values in the
melt were not dropped.
You can partially test for the second problem using table. Visually check that all levels of "variable" have the same length. This is not fool proof, but is a pretty good indicator.