I have some data in long form that looks like this:
dat1 = data.frame(
id = rep(LETTERS[1:2], each=4),
value = 1:8
)
In table form:
id value
A 1
A 2
A 3
A 4
B 5
B 6
B 7
B 8
And I want it to be in short form and look like this:
dat1 = data.frame(A = 1:4, B = 5:8)
In table form:
A B
1 5
2 6
3 7
4 8
Now I could solve this by looping with cbind()
and stuff, but I want to use some kind of reshape/melt function as these are the best way to do this kind of thing I think.
However, from spending >30 minutes trying to get melt()
and reshape()
to work, reading answers on SO, it seems that these functions requires the id.var
to be set. Now, it is plainly redundant for this kind of thing, so how do I do what I want to do without having to resort to some kind of looping?
Here's a base R approach to consider. It uses the
lengths
function, which I believe was introduced in R 3.2.I'm pretty sure this has been answered before. Anyway,
unstack
is convenient in this particular case with equal group size:Solution below works when there are different numbers of As and Bs. For equal counts,
unstack
works great and with less code (Henrik's answer).initial data:
result: