2012-07-27 46 views
2

我想创建这样一个数据帧:被列名的每一行匹配值填充列值

Label Jim Charles Kevin Alan 
Charles 0 1  0  0 
Kevin 0 0  1  0 
Alan 0 0  0  1 
Alan 0 0  0  1 
Jim  1 0  0  0 

我开始与其中列名都设置一个数据帧和别人的名字列在第一列中,但所有数字均为0.我希望通过将第一列中列出的名称与列名称进行匹配,可以快速将其中一些设置为1。

回答

2

类似本的回答,如果你的数据是在一个叫做df的数据框里:

df <- structure(list(Label = c("Charles", "Kevin", "Alan", "Alan", 
"Jim"), Jim = c(0, 0, 0, 0, 0), Charles = c(0, 0, 0, 0, 0), Kevin = c(0, 
0, 0, 0, 0), Alan = c(0, 0, 0, 0, 0)), .Names = c("Label", "Jim", 
"Charles", "Kevin", "Alan"), row.names = c(NA, -5L), class = "data.frame") 

df[outer(df$Label, names(df), '==')] <- 1 
+0

我认为这匹配OP的数据结构比我的答案更好(尽管数字矩阵可能会更好/更有效的方式来存储这样的数据......它甚至可能想成为一个稀疏矩阵.. ) – 2012-07-27 19:58:05

+0

@BenBolker是的,但你是光滑的!我不知道'storage.mode'! – Justin 2012-07-27 19:59:51

3

可能有一个更快的方法,但这应该工作得相当好:

数据:

m <- matrix(0,nrow=5,ncol=4, 
      dimnames=list(c("Charles","Kevin","Alan","Alan","Jim"), 
      c("Jim","Charles","Kevin","Alan"))) 

使用outer所有行与所有列的比较:

mm <- outer(rownames(m),colnames(m),"==") 
storage.mode(mm) <- "numeric" ## because as.numeric() loses matrix dimensions 
dimnames(mm) <- dimnames(m) ## reset row/column names