Cleaner way of constructing binary matrix from vector

后端 未结 2 1077
旧时难觅i
旧时难觅i 2020-12-22 02:08

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

2条回答
  •  温柔的废话
    2020-12-22 02:38

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

    The columns in result you may rename.

    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.matrix was a little bit faster then table

    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
    

提交回复
热议问题