这是一些示例数据
>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
感谢
答案 0 :(得分:4)
尝试dcast
library(reshape2)
dcast(mydat, id~treat, value.var='treat', length)
或者
table(mydat)
或者
xtabs(rep(1, nrow(mydat))~id+treat, mydat)
答案 1 :(得分:1)
以下是dplyr
和tidyr
解决方案
library(dplyr)
library(tidyr)
mydat %>% count(id, treat) %>% spread(treat, n, fill = 0)