在 R 中重塑从长到宽的重复测量

reshape repeated measurements long to wide in R

这里是一些示例数据

>mydat <- data.frame(id=c(rep(1,6),rep(2,4)),treat=c("a","a","a","b","b","c","a","b","d","f"))
>mydat
id treat
1   1     a
2   1     a
3   1     a
4   1     b
5   1     b
6   1     c
7   2     a
8   2     b
9   2     d
10  2     f

如何计算每个 id 的处理并将它们放在单独的列中?

它应该是这样的:

>result <- data.frame(id=c(1,2),a=c(3,1),b=c(2,1),c=c(1,0),d=c(0,1),f=c(0,1))
>result
    id a b c d f
  1  1 3 2 1 0 0
  2  2 1 1 0 1 1

谢谢

尝试dcast

library(reshape2)
dcast(mydat, id~treat, value.var='treat', length)

或者

 table(mydat)

或者

 xtabs(rep(1, nrow(mydat))~id+treat, mydat)

这是dplyrtidyr的解决方案

library(dplyr)
library(tidyr)
mydat %>% count(id, treat) %>% spread(treat, n, fill = 0)