Using:
library(reshape2)
recast(dat, serialno ~ value, id.var = 'serialno', fun.aggregate = length)
gives:
serialno A B C CA D FL GA NJ NY PA WA
1 100 2 0 1 1 1 1 0 0 0 0 0
2 101 0 1 0 1 1 0 0 0 0 0 0
3 102 1 0 1 0 0 0 1 0 0 0 0
4 103 1 1 2 0 0 0 0 0 0 1 1
5 104 0 2 1 2 1 0 0 0 0 0 0
6 105 1 1 1 0 1 0 0 1 1 0 0
Or:
library(dplyr)
library(tidyr)
dat %>%
gather(key, val, state:type2) %>%
group_by(serialno, val) %>%
tally() %>%
spread(val, n, fill = 0)
Or:
library(data.table)
dcast(melt(setDT(dat), id = 1), serialno ~ value, fun.aggregate = length)
Or (per @Frank's suggestion):
res <- table(melt(dat, id="serialno")[, c("serialno","value")])
print(res, zero.print="")
Of which the last one results in:
value
serialno A B C CA D FL GA NJ NY PA WA
100 2 1 1 1 1
101 1 1 1
102 1 1 1
103 1 1 2 1 1
104 2 1 2 1
105 1 1 1 1 1 1
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…