Skip to content

Converting a dataframe to a matrix

1 message · Mark Leeds

#
Hi: Below works but it's extremely ugly and overly complicated. i'm sure 
someone else will send you something better  and I'll be waiting also.
Also, the way I named the rows and columns works for below but it won't 
hold in the general case if you don't have nice ordered names like
you do below. So, use it until we something better.

DF <- read.table(textConnection("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"),header=TRUE,stringsAsFactors=FALSE)


mat <- matrix(sapply(1:nrow(DF),function(.row) {
     DF[.row,3]
 
}),nrow=length(unique(DF$name)),byrow=TRUE,dimnames=list(c(unique(DF$name)),c(unique(DF$color))))

print(mat)
On Wed, Mar 11, 2009 at 12:42 AM, Jennifer Brea wrote: