说我有以下的基质mat,这是水平的二进制指示符矩阵A,B和C用于一组5个的观察:
mat <- matrix(c(1,0,0,
1,0,0,
0,1,0,
0,1,0,
0,0,1), ncol = 3, byrow = TRUE)
colnames(mat) <- LETTERS[1:3]
> mat
A B C
[1,] 1 0 0
[2,] 1 0 0
[3,] 0 1 0
[4,] 0 1 0
[5,] 0 0 1
Run Code Online (Sandbox Code Playgroud)
我想将其转换为单个因子,使输出等效fac定义为:
> fac <- factor(rep(LETTERS[1:3], times = c(2,2,1)))
> fac
[1] A A B B C
Levels: A B C
Run Code Online (Sandbox Code Playgroud)
如果您从字母组合中获取标签,则会有额外的分数mat,但是一组数字代码(例如c(1,1,2,2,3))也可以作为所需的输出.
TMS*_*TMS 15
矩阵乘法的优雅解决方案(迄今为止最短):
as.factor(colnames(mat)[mat %*% 1:ncol(mat)])
Run Code Online (Sandbox Code Playgroud)
该解决方案利用了arr.ind=TRUE参数which,将匹配位置作为数组位置返回.然后将它们用于索引colnames:
> factor(colnames(mat)[which(mat==1, arr.ind=TRUE)[, 2]])
[1] A A B B C
Levels: A B C
Run Code Online (Sandbox Code Playgroud)
分解为步骤:
> which(mat==1, arr.ind=TRUE)
row col
[1,] 1 1
[2,] 2 1
[3,] 3 2
[4,] 4 2
[5,] 5 3
Run Code Online (Sandbox Code Playgroud)
使用第二列的值,即which(...)[, 2]索引colnames:
> colnames(mat)[c(1, 1, 2, 2, 3)]
[1] "A" "A" "B" "B" "C"
Run Code Online (Sandbox Code Playgroud)
然后转换为一个因素
一种方法是使用矩阵直接按行号和索引复制名称,然后将其包装factor以恢复级别:
factor(rep(colnames(mat), each = nrow(mat))[as.logical(mat)])
[1] A A B B C
Levels: A B C
Run Code Online (Sandbox Code Playgroud)
如果这是从model.matrix,该colnames已经fac预先考虑,所以这应该工作一样,但去除多余的文字:
factor(gsub("^fac", "", rep(colnames(mat), each = nrow(mat))[as.logical(mat)]))
Run Code Online (Sandbox Code Playgroud)