从向量构建二进制矩阵的更简洁方法 [英] Cleaner way of constructing binary matrix from vector

查看:29
本文介绍了从向量构建二进制矩阵的更简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有趣的挑战:我试图从一个整数向量构造一个二元矩阵.二元矩阵应包含与向量长度一样多的行,以及与整数向量中最大值一样多的列.矩阵中的第 i 行将对应向量的第 i 个元素,该行在位置 j 处包含一个 1,其中 j 等于向量的第 i 个元素的值;否则,该行包含零.如果第 i 个整数的值为 0,则整个第 i 行应为 0.

I have a fun challenge: I'm trying to construct a a binary matrix from an integer vector. The binary matrix should contain as many rows as the length of vector, and as many columns as the max value in the integer vector. The ith row in the matrix will correspond to the ith element of the vector, with the row containing a 1 at the position j, where j is equal to the value of the ith element of the vector; otherwise, the row contains zeros. If the value of the ith integer is 0, then the whole ith row should be 0.

为了让这一切变得更简单,这里有一个可重现的工作示例:

To make this a whole lot simpler, here is a working reproducible example:

set.seed(1)
playv<-sample(0:5,20,replace=TRUE)#sample integer vector

playmat<-matrix(playv,nrow=length(playv),ncol=max(playv))#create matrix from vector

for (i in 1:length(playv)){
pos<-as.integer(playmat[i,1])
playmat[i,pos]<-1
playmat[i,-pos]<-0}

    head(playmat)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    0    0
[2,]    0    1    0    0    0
[3,]    0    0    1    0    0
[4,]    0    0    0    0    1
[5,]    1    0    0    0    0
[6,]    0    0    0    0    1

上述解决方案是正确的,我只是想让一些更强大的东西.

The above solution is correct, I'm just looking to make something more robust.

推荐答案

set.seed(1)
playv <- sample(0:5,20,replace=TRUE)
playv <- as.character(playv)
results <- model.matrix(~playv-1)

result 中的列可以重命名.

我喜欢 Ananda Mahto 提供的解决方案,并将其与 model.matrix 进行了比较.这是一个代码

I like the solution provided by Ananda Mahto and compared it to model.matrix. Here is a code

library(microbenchmark)

set.seed(1)
v <- sample(1:10,1e6,replace=TRUE)

f1 <- function(vec) {
  vec <- as.character(vec)
  model.matrix(~vec-1)
}

f2 <- function(vec) {
  table(sequence(length(vec)), vec)
}

microbenchmark(f1(v), f2(v), times=10)

model.matrixtable

Unit: seconds
  expr      min       lq   median       uq      max neval
 f1(v) 2.890084 3.147535 3.296186 3.377536 3.667843    10
 f2(v) 4.824832 5.625541 5.757534 5.918329 5.966332    10

这篇关于从向量构建二进制矩阵的更简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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