2

I have a dataset like so:

  Name    |   Pet    | isTrain  | 
---------------------------------
 Ben      | Dog      |    1     | 
 Kim      | Cat      |    0     | 
 Kim      | Rabbit   |    0     | 

How do I make this into a matrix in R where the Name is the row and the Pet is the column, and isTrain is the value?

Eisen
  • 1,697
  • 9
  • 27

1 Answers1

0

We can use xtabs from base R

xtabs(isTrain ~ Name + Pet, df1)
# Pet
#Name  Cat Dog Rabbit
#  Ben   0   1      0
#  Kim   0   0      0

data

df1 <- data.frame(Name = c('Ben', 'Kim', 'Kim'),
     Pet = c('Dog', 'Cat', 'Rabbit'), isTrain = c(1, 0, 0))
akrun
  • 874,273
  • 37
  • 540
  • 662