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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With