r - Making a list of zeros and ones from a large list -


i have large list looks this:

1
2
3
3

and need create list looks this:

 |------|------|------|------|  |   1  |    1 |  0   |   0  |  |------|------|------|------|  |   2  |   0  |  1   |  0   |   |------|------|------|------|  |   3  |   0  |   0  |  1   |  |------|------|------|------|  |   3  |   0  |   0  |  1   |  |------|------|------|------| 

i have tried using loops, , method detailed here:

create mutually exclusive dummy variables categorical variable in r

but because dataset large, run memory constraints.

am thinking of using split, apply, combine technique, not able desired result.

help appreciated!

here ways:

1) outer gives matrix result:

x <- c(1, 2, 3, 3) outer(x, unique(x), "==") + 0 

giving:

     [,1] [,2] [,3] [1,]    1    0    0 [2,]    0    1    0 [3,]    0    0    1 [4,]    0    0    1 

2) model.matrix gives matrix result.

fx <- factor(x) model.matrix(~ fx + 0) 

giving:

  fx1 fx2 fx3 1   1   0   0 2   0   1   0 3   0   0   1 4   0   0   1 attr(,"assign") [1] 1 1 1 attr(,"contrasts") attr(,"contrasts")$fx [1] "contr.treatment" 

3) sparsematrix uses sparse matrix internal representation result not use storage zeros.

library(matrix)  # ok example sparsematrix(seq_along(x), x)    # if x not contain sequence numbers use instead sparsematrix(seq_along(x), as.numeric(factor(x))) 

giving:

4 x 3 sparse matrix of class "dgcmatrix"      [1,] 1 . .     [2,] . 1 .     [3,] . . 1     [4,] . . 1 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -