将列表转换为是/否的数据帧

时间:2015-06-04 01:39:56

标签: r

我有一个值的数据框,我试图变成一个双模矩阵。第一个数据框包含人和游戏(按ID)。我试图将其变成一个列出所有游戏以及一个人是否拥有它们的数据框。有人可以解释如何在R中执行此操作,还是这个问题更适合另一种编程语言?

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

1 个答案:

答案 0 :(得分:3)

首先为结果创建一个空矩阵:

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

然后创建索引矩阵,将这些条目设置为1:

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

将这些条目设置为1:

r[x] <- 1

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