Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a matrix of zeros and ones from R

Tags:

r

matrix

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

like image 303
student_R123 Avatar asked Jun 01 '21 15:06

student_R123


People also ask

How do you make a matrix with zeros in R?

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.

How do you make a matrix of all ones in R?

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.

How do I create a matrix from a Dataframe in R?

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.


Video Answer


1 Answers

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))
like image 198
akrun Avatar answered Nov 15 '22 05:11

akrun