I have a data frame that looks like this:
a b
1 x 8
2 x 6
3 y 3
4 y 4
5 z 5
6 z 6
and I want to turn it into this:
x y
You can do this with dcast
and rowid
from the data.table package as well:
dat <- dcast(setDT(df), rowid(a) ~ a, value.var = "b")[,a:=NULL]
which gives:
> dat x y z 1: 8 3 5 2: 6 4 6
Old solution:
# create a sequence number by group
setDT(df)[, r:=1:.N, by = a]
# reshape to wide format and remove the sequence variable
dat <- dcast(df, r ~ a, value.var = "b")[,r:=NULL]
which gives:
> dat x y z 1: 8 3 5 2: 6 4 6