在R中将因子矩阵转换为二进制(指标)矩阵的最有效方法 [英] Most efficient way to turn factor matrix into binary (indicator) matrix in R
本文介绍了在R中将因子矩阵转换为二进制(指标)矩阵的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以想到几种方法来转换这种类型的矩阵(数据框):
I can think of several ways to turn matrix (data frame) of this type:
dat = data.frame(
x1 = rep(c('a', 'b'), 100),
x2 = rep(c('x', 'y'), 100)
)
head(dat)
x1 x2
1 a x
2 b y
3 a x
4 b y
5 a x
6 b y
像这样变成二进制(指标)矩阵(或数据帧):
Into a binary (indicator) matrix (or data frame) like this:
a b x y
1 0 1 0
0 1 0 1
...
(此结构当然是微不足道的,仅用于说明目的!)
(This structure is, of course, trivial and only for illustrative purpose!)
非常感谢!
推荐答案
我们可以使用table
tbl <- table(rep(1:nrow(dat),2),unlist(dat))
head(tbl, 2)
# a b x y
# 1 1 0 1 0
# 2 0 1 0 1
或者可能是有效的选择
Or a possibly efficient option would be
library(Matrix)
sM <- sparse.model.matrix(~ -1 + x1 +x2, dat,
contrasts.arg = lapply(dat, contrasts, contrasts = FALSE))
colnames(sM) <- sub(".*\\d", "", colnames(sM))
head(sM, 2)
# 2 x 4 sparse Matrix of class "dgCMatrix"
# a b x y
#1 1 . 1 .
#2 . 1 . 1
可以通过转换为matrix
head(as.matrix(sM),2)
# a b x y
#1 1 0 1 0
#2 0 1 0 1
这篇关于在R中将因子矩阵转换为二进制(指标)矩阵的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文