将R因子转换为二进制矩阵值 [英] Converting R Factors into Binary Matrix Values

查看:88
本文介绍了将R因子转换为二进制矩阵值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据框转换为一个矩阵,该矩阵将一个因子列扩展为多个因子列,并根据因子分配一个1/0.例如

I would like to convert my dataframe into a matrix that expands a single factor column into multiple ones and assigns a 1/0 depending on the factor. For example

C1 C2 C3
A  3  5
B  3  4
A  1  1

应该变成类似

C1_A C1_B C2 C3
1      0  3  5
0      1  3  4
1      0  1  1

如何在R中做到这一点?我尝试了data.matrixas.matrix,但没有返回我想要的内容.他们为单个因子列分配一个整数"值,没有扩展.

How can I do this in R? I tried data.matrix, as.matrix which did not return what I wanted. They assign an "integer" value to a single factor column, there is no expansion.

推荐答案

假设dat是您的数据框:

cbind(dat, model.matrix( ~ 0 + C1, dat))

  C1 C2 C3 C1A C1B
1  A  3  5   1   0
2  B  3  4   0   1
3  A  1  1   1   0

此解决方案适用于任意数量的因子水平,而无需手动指定列名.

This solution works with any number of factor levels and without manually specifying column names.

如果要排除列C1,则可以使用以下命令:

If you want to exclude the column C1, you could use this command:

cbind(dat[-1], model.matrix( ~ 0 + C1, dat))

这篇关于将R因子转换为二进制矩阵值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆