Change from long to wide format with indicators
All-
I am needing to change from a long format to a wide format in R, but I need the column values to be 1 or zero depending on if the particular variable is present for the subject.
The input data looks like:
Subject Produc开发者_运维百科t
1 ProdA
1 ProdB
1 ProdC
2 ProdB
2 ProdC
2 ProdD
3 ProdA
3 ProdB
and I want it to be
Subject ProdA ProdB ProdC ProdD
1 1 1 1 0
2 0 1 1 1
3 1 1 0 0
Is there any way in R to accomplish this?
EDIT:
One way I think is to first table the data:
tbl<-data.frame(table(data))
Then apply
final <- cast(tbl, Subject~Product, max)
I wonder if there is a more efficient way?
xtabs(data=dat)
Product
Subject ProdA ProdB ProdC ProdD
1 1 1 1 0
2 0 1 1 1
3 1 1 0 0
A slightly more readable version would make the fiormula explicit:
xtabs( ~Subject+Product, data=dat)
If you want to go with stats::reshape, then try this:
reshape(dat, idvar="Subject", timevar=2, v.names="Product", direction="wide")
Subject Product.ProdA Product.ProdB Product.ProdC Product.ProdD
1 1 ProdA ProdB ProdC <NA>
4 2 <NA> ProdB ProdC ProdD
7 3 ProdA ProdB <NA> <NA>
(But it does not return numbers.)
精彩评论