4

如果我有一个因子变量,比如x = factor(c(1, 2, 3)),那么我可以使用model.matrix函数来生成一个虚拟矩阵:

model.matrix(~x + 0)

我会得到一个像这样的矩阵:

  x1 x2 x3
1  1  0  0
2  0  1  0
3  0  0  1

我的问题是,如果我已经有一个很大的虚拟矩阵,我怎么能把它融化回(因子)列?

在另一个世界中,是否存在 的反函数model.matrix

4

1 回答 1

3

apply适合这个。

我将使用caret包的cars数据,它有 1-0 的数据,而不是因子格式的汽车类型。让我们将这 5 列 ( convertible, coupe, hatchback, sedan, wagon) 转换为单因素变量Type

library(caret)
data(cars)
head(cars[,-c(1:13)])

  convertible coupe hatchback sedan wagon
1           0     0         0     1     0
2           0     1         0     0     0
3           1     0         0     0     0
4           1     0         0     0     0
5           1     0         0     0     0
6           1     0         0     0     0


cars$Type = as.factor(apply(df,1,function(foo){return(names(df)[which.max(foo)])}))

head(cars[,-c(1:13)])

  convertible coupe hatchback sedan wagon        Type
1           0     0         0     1     0       sedan
2           0     1         0     0     0       coupe
3           1     0         0     0     0 convertible
4           1     0         0     0     0 convertible
5           1     0         0     0     0 convertible
6           1     0         0     0     0 convertible
于 2015-04-30T16:08:13.697 回答