Convert list to dataframe yes / no

I have a dataframe of values ​​that I am trying to turn into a bi-mode matrix. The first data block contains people and games (by id). I am trying to turn this into a dataframe that lists all the games and whether they have a person or not. Can someone explain how to do this in R, or is this a question that suits another programming language better?

df<-data.frame(c(1,4,1),c(2,2,3),c(3,1,NA)) #note person3 only has 2 games... all empty spaces are filled with NA
row.names(df)<-c("person1","person2","person3")
colnames(df)<-c("game","game","game")
df
##         game game game
## person1    1    2    3
## person2    4    2    1
## person3    1    3   NA

res<-data.frame(c(1,1,1),c(1,1,0),c(1,0,1),c(0,1,0))
colnames(res)<-c("1","2","3","4")
row.names(res)<-c("person1","person2","person3")
res
##         1 2 3 4
## person1 1 1 1 0
## person2 1 1 0 1
## person3 1 0 1 0

      

+3


source to share


1 answer


First, create an empty matrix for the results:

r <- matrix(0, nrow=nrow(df), ncol=max(df, na.rm=TRUE))
row.names(r) <- row.names(df)

      

Then create an index matrix, these entries will be set to 1:



x <- matrix(c(as.vector(row(df)), as.vector(as.matrix(df))), ncol=2)

      

Set these entries to 1:

r[x] <- 1

r
##         [,1] [,2] [,3] [,4]
## person1    1    1    1    0
## person2    1    1    0    1
## person3    1    0    1    0

      

+3


source







All Articles