Reputation: 13
I have a list of my results in R in the format:
Result:
Cat1
Cat2
Cat1
Cat3
...
I need to get it into the format:
Results:
....Cat 1.....Cat 2.....Cat3
1 0 0
0 1 0
1 0 0
0 0 1
I know this is a basic question, but without knowing the terms to search for I am having a very difficult time finding an answer. Thank you very much for your time.
Upvotes: 1
Views: 39
Reputation: 887891
I guess you need model.matrix
model.matrix(~0+Category, df1)
# CategoryCat1 CategoryCat2 CategoryCat3
#1 1 0 0
#2 0 1 0
#3 1 0 0
#4 0 0 1
#attr(,"assign")
#[1] 1 1 1
#attr(,"contrasts")
#attr(,"contrasts")$Category
#[1] "contr.treatment"
Or use table
table(1:nrow(df1), df1$Category)
# Cat1 Cat2 Cat3
# 1 1 0 0
# 2 0 1 0
# 3 1 0 0
# 4 0 0 1
df1 <- structure(list(Category = c("Cat1", "Cat2", "Cat1", "Cat3")),
.Names = "Category", class = "data.frame", row.names = c(NA, -4L))
Upvotes: 1