我的数据框看起来像这样:
category fan_id likes
A 10702397 1
B 10702397 4
A 35003154 1
B 35003154 1
C 35003154 2
我想将其转换为以下数据框
fan_id A B C
10702397 1 4 0
35003154 1 1 2
我能想到的唯一方法是遍历数据框并手动构造另一个,但似乎必须有一种更好的方法。
好像我想与这里所问的相反Switch column to row in a data.frame
最佳答案
> library(reshape2)
> dat <- data.frame(category=c("A","B","A","B","C"),fan_id=c(10702397,10702397,35003154,35003154,35003154),likes=c(1,4,1,1,2))
> dcast(dat,fan_id~category,fill=0)
Using likes as value column: use value.var to override.
fan_id A B C
1 10702397 1 4 0
2 35003154 1 1 2