1

here is some example data

>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

how can I count the treatments for each id and put them in a separate column?

It should look like this:

>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

thanks

spore234
  • 3,550
  • 6
  • 50
  • 76

2 Answers2

4

try dcast

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

Or

 table(mydat)

Or

 xtabs(rep(1, nrow(mydat))~id+treat, mydat)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Here is a dplyr and tidyr solution

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