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第一列到列名。

4

2 回答 2

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
于 2012-07-27T19:53:23.627 回答
2

与 Ben 的回答类似,如果您的数据位于名为的 data.frame 中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
于 2012-07-27T19:56:01.997 回答