数据包含两个变量:id 和grade。每个id可以有多个记录
每个年级。
dat <- data.frame(id = c(1,1,1,2,2,2,2,3,3,4,5,5,5),
grade = c("a", "b", "c", "a", "a", "b", "b", "d", "f", "c", "a", "e", "f"))
我想将数据重塑为宽形状,以便每个 id 只有一条记录
每个独特的等级都成为一列。每列的值为 0 或 1,
取决于每个id的等级。
最终的数据集如下所示:
id a b c d e f
1 1 1 1 0 0 0
2 1 1 0 0 0 0
3 0 0 0 1 0 1
4 0 0 1 0 0 0
5 1 0 0 0 1 1
我尝试过这个,但没有运气。
n.dat <- reshape(dat, timevar = "grade",idvar = c("id"),direction = "wide")