R:如何将有序因子转换为虚拟变量?

时间:2017-08-15 10:31:07

标签: r dummy-variable

例如。具有有序等级的因子

[1] 0 0 6 6 3 4 Levels: 0 < 1 < 2 < 3 < 4 < 5 < 6

应转换为

ti0 ti1 ti2 ti3 ti4 ti5 ti6 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0

我查看过像dummies这样的软件包以及类似model.matrix的函数但是无法找到解决方案。

2 个答案:

答案 0 :(得分:1)

这似乎有效。

x <- factor(c("0", "0", "6", "6", "3", "4"), levels = 0:6, ordered = TRUE)

out <- matrix(0, nrow = length(x), ncol = max(as.numeric(x)))

for (i in 1:length(x)) {
  out[i, 1:as.numeric(x[i])] <- 1
}
colnames(out) <- paste("ti", levels(x), sep = "")


     ti0 ti1 ti2 ti3 ti4 ti5 ti6
[1,]   1   0   0   0   0   0   0
[2,]   1   0   0   0   0   0   0
[3,]   1   1   1   1   1   1   1
[4,]   1   1   1   1   1   1   1
[5,]   1   1   1   1   0   0   0
[6,]   1   1   1   1   1   0   0

答案 1 :(得分:0)

如果您的目的是使用自定义对比矩阵创建变量,并且在您的情况下,您似乎正在创建here描述的累积编码序数变量,则可以执行以下操作。

nav class="navbar navbar-expand-lg bg-dark text-white">
    <div class="container-fluid">
    <a class="navbar-brand" id="button-menu"><i class="fa fa-bars" aria-hidden="true"></i> Menu</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
    <i class="fa fa-bars" aria-hidden="true" style="color: #ffffff;"></i>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
        <ul class="navbar-nav ml-auto">
        <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Alerts <i class="fa fa-chevron-down" aria-hidden="true"></i></a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="">Right Link</a>
          <a class="dropdown-item" href="">Members Waiting Approval <span class="badge badge-primary"><?php echo $newmember;?></span>
        </a>
        </div>
        </li>
        <li class="nav-item">
            <a href="<?php echo base_url('admin/members/logout');?>" class="nav-link">Logout</a>
        </li>
        </ul>
    </div>
    </div>
</nav>

这个&#39;定制&#39;变量可以直接用于其他函数(例如回归方程),而无需手动创建虚拟变量。