r - Transforming list into dataframe of yes/no -
i have dataframe of values trying turn two-mode matrix. first dataframe contains people , games (by id). trying turn dataframe lists games , whether person has them or not. can explain how in r, or question better suited programming language?
df<-data.frame(c(1,4,1),c(2,2,3),c(3,1,na)) #note person3 has 2 games... empty spaces filled 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
first create empty matrix results:
r <- matrix(0, nrow=nrow(df), ncol=max(df, na.rm=true)) row.names(r) <- row.names(df)
then create index matrix, entries set 1:
x <- matrix(c(as.vector(row(df)), as.vector(as.matrix(df))), ncol=2)
set entries 1:
r[x] <- 1 r ## [,1] [,2] [,3] [,4] ## person1 1 1 1 0 ## person2 1 1 0 1 ## person3 1 0 1 0
Comments
Post a Comment