基reshape
函数方法:
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)
)
result <- reshape(dat,idvar="fan_id",timevar="category",direction="wide")
names(result)[2:4] <- gsub("^.*\\.","",names(result)[2:4])
result
fan_id A B C
1 10702397 1 4 NA
3 35003154 1 1 2
奖励xtabs
方式:
result2 <- as.data.frame.matrix(xtabs(likes ~ fan_id + category, data=dat))
A B C
10702397 1 4 0
35003154 1 1 2
带有修复的确切格式:
data.frame(fan_id=rownames(result2),result2,row.names=NULL)
fan_id A B C
1 10702397 1 4 0
2 35003154 1 1 2