如果我有一个因子变量,比如 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
的反函数? ?
最佳答案
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
关于r - 将虚拟矩阵融化为一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29368565/