Sam Pepe Sam Pepe - 1 month ago 15
R Question

Converting two columns into matrix form

I have two columns that I would like to convert into a matrix that includes binaries as its contents. For example:

If these were the columns(Name and animal):

Name Animal
Jen Cat
Sam Dog
Pat Hamster
Ann Fish
Lea Cat
Jen Hamster
Sam Hamster
Jen Fish


I would want to transform it to this format:

Cat Dog Hamster Fish
Jen 1 0 1 1
Sam 0 1 1 0
Pat 0 0 1 0
Ann 0 0 0 1
Lea 1 0 0 0

Answer

Other than table that is mentioned by @zx8754 in comments:

table(df$Name, df$Animal)

You could also use xtabs as follows:

xtabs(Col~Name+Animal, cbind(df,Col=1))

#     Animal
#Name  Cat Dog Fish Hamster
#  Ann   0   0    1       0
#  Jen   1   0    1       1
#  Lea   1   0    0       0
#  Pat   0   0    0       1
#  Sam   0   1    0       1

data

df <- structure(list(Name = structure(c(2L, 5L, 4L, 1L, 3L, 2L, 5L, 
2L), .Label = c("Ann", "Jen", "Lea", "Pat", "Sam"), class = "factor"), 
    Animal = structure(c(1L, 2L, 4L, 3L, 1L, 4L, 4L, 3L), .Label = c("Cat", 
    "Dog", "Fish", "Hamster"), class = "factor")), .Names = c("Name", 
"Animal"), class = "data.frame", row.names = c(NA, -8L))
Comments