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.
Doesn’t the following work?
I suspect, though, that you’re asking a little bit different question (as mentioned in my comment). In particular, what if you were starting with:
With base R’s
reshape, it’s just one line:Let’s try the same with
dcastfrom “reshape2”. Here’s the approach we might be tempted to take:But that doesn’t work because
dcastexpects a singlevalue.var. So, we need tomeltthe data again.Now, we can use
dcastquite easily.