Skip to content

Converting a dataframe to a matrix

3 messages · Jennifer Brea, Simon Blomberg, justin bem

#
If I have a dataframe which is organized like this:

   name color likes?
1 sally   red    0
2 sally  blue    1
3 sally green    1
4  jake   red    0
5  jake  blue    1
6  jake green    1
7   tom   red    1
8   tom  blue    0
9   tom green    0


And I want to create a matrix in the form:

      red blue green
sally   0    1     1
jake    0    1     1
tom     1    0     0


Are there any built-in commands that might help me do this?  Also, I 
can't assume that there is an observation for every person-color.  In 
other words, in the original dataset, there might be some colors for 
which sally offered no opinion.  In some cases, this may be represented 
by NA, in others, it may mean that no row exists for sally for that color.

Thank you!
#
xtabs is your friend:

xtabs(likes ~ color + name, data=dat)

       color
name    blue green red
  jake     1     1   0
  sally    1     1   0
  tom      0     0   1

See ?xtabs for more info. Note that I changed the "likes?" column to
just "likes". It is a bad idea to have question marks in variable names.

Simon.
On Wed, 2009-03-11 at 01:42 -0400, Jennifer Brea wrote: