Suppose I've got the following data frame :
d <- data.frame(id=c(1,1,1,2,2,3,3,3), time=c(1,2,3,1,2,1,2,3), var=runif(8))
d
id time var
1 1 1 0.3733586
2 1 2 0.5743769
3 1 3 0.8253280
4 2 1 0.8136957
5 2 2 0.8726963
6 3 1 0.1105549
7 3 2 0.9527002
8 3 3 0.5690021
With the base reshape
function, I can transform it to a "wide" format by specifying a ìdvar
(which identifies rows belonging to the same unit) and a timevar
(which identifies different observations of the same unit) :
reshape(d, idvar="id", timevar="time", direction="wide")
id var.1 var.2 var.3
1 1 0.3733586 0.5743769 0.8253280
4 2 0.8136957 0.8726963 NA
6 3 0.1105549 0.9527002 0.5690021
I've tried to do it with the dcast
function of reshape2
, but didn't find a way. Do you know if it is possible ?
EDIT : Ananda Mahto's comment and answer are perfectly right, the real question was to cast the original data frame when it has several var
columns. My example was not appropriate, sorry.