I have a dateframe as such:
long <- data.frame(subj = c(1,1,2,2,2), code = c(\"a\", \"b\", \"a\", \"d\", \"e\"))
subj code
1 1 a
2 1 b
We create a sequence column for the grouping column 'subj' and then do dcast
. We can use dcast
from data.table
. Convert the 'data.frame' to 'data.table' (setDT(long)
), grouped by 'subj', create the sequence column 'new' and reshape from 'long' to 'wide' with dcast
.
library(data.table)#v1.9.6+
setDT(long)[, new:=paste('code', 1:.N, sep='.'), by = subj]
dcast(long, subj~new, value.var='code')
Or this can be done with spread
from tidyr
after creating the sequence column using dplyr
methods
library(dplyr)
library(tidyr)
long %>%
group_by(subj) %>%
mutate(new=paste('code', row_number(), sep='.')) %>%
spread(new, code)