Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn numeric vector into boolean matrix [duplicate]

I have a column vector in a dataframe and would like to turn it into a binary matrix so I can do matrix multiplication with it later on.

y_labels
1
4
4
3

desired output

1 0 0 0
0 0 0 1
0 0 0 1
0 0 1 0

In Octave I would do something like y_matrix = (y_labels == [1 2 3 4]). However, I can't figure out how to get this in R. Anybody know how?

like image 381
zipline86 Avatar asked Aug 22 '26 13:08

zipline86


1 Answers

We can use model.matrix to change it to binary

model.matrix(~ -1 + factor(y_labels, levels = 1:4), df1)

or with table

with(df1, table(1:nrow(df1), factor(y_labels, levels = 1:4)))
#    1 2 3 4
#  1 1 0 0 0
#  2 0 0 0 1
#  3 0 0 0 1
#  4 0 0 1 0

Or more compactly

+(sapply(1:4, `==`, df1$y_labels))
#      [,1] [,2] [,3] [,4]
#[1,]    1    0    0    0
#[2,]    0    0    0    1
#[3,]    0    0    0    1
#[4,]    0    0    1    0
like image 103
akrun Avatar answered Aug 25 '26 17:08

akrun