I want to create a matrix of 0s and 1s based on the following data.
id <-c(1,1,1,2,2,3)
x<- c(5,7,8,2,6,5)
data_toy <- data.frame(id,x)
data_toy%>% count(id)
> data_toy%>% count(id)
id n
1 1 3
2 2 2
3 3 1
So based on the data, I need to create a 6X3 matrix where first column should be (1,1,1,0,0,0) and second column should be (0,0,0,1,1,0) so on.
Can you suggest anything to do this?
Thank you
Using rep() method rep() method in R can be used to create a one row matrix, which creates the number of columns equivalent to the value in the second argument of the method. The first argument, specifies the vector to repeat and stack together y times, which in this case is 0. We can specify 0L instead of 0.
In R, you create an all-ones matrix with the matrix() function. This basic R function requires 3 arguments, namely the value (i.e., the number 1), the number of rows, and the number of columns. You can use the matrix() function to create square and non-square all-ones matrices.
Convert a Data Frame into a Numeric Matrix in R Programming – data. matrix() Function. data. matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.
We can use model.matrix
in base R
model.matrix(~ factor(id) - 1, data_toy)
-output
# factor(id)1 factor(id)2 factor(id)3
#1 1 0 0
#2 1 0 0
#3 1 0 0
#4 0 1 0
#5 0 1 0
#6 0 0 1
Or use table
with(data_toy, table(seq_along(id), id))
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