Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert table() to matrix in r

Tags:

r

matrix

I have a 6x6 matrix as shown below:

M = matrix(0,nrow = 6, ncol = 6);
for(i in 1:6)
  for(j in 1:6)
    M[i,j]<- i+j

M is a 6x6 matrix with elements:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2    3    4    5    6    7
[2,]    3    4    5    6    7    8
[3,]    4    5    6    7    8    9
[4,]    5    6    7    8    9   10
[5,]    6    7    8    9   10   11
[6,]    7    8    9   10   11   12

I want to derive a matrix of elements with their frequencies from above matrix M using r function table().

the output of table(M) is:

> table(M)
M
 2  3  4  5  6  7  8  9 10 11 12 
 1  2  3  4  5  6  5  4  3  2  1 

How to simply make a 11x2 matrix from table(M) output?

I tried as.matrix(table(M)) but it makes the elements as row names although I am not sure what's happening!

> as.matrix(table(M))
   [,1]
2     1
3     2
4     3
5     4
6     5
7     6
8     5
9     4
10    3
11    2
12    1

As suggested:

DF <- data.frame(table(M))
ma <- data.matrix(DF)

      M Freq
 [1,]  1    1
 [2,]  2    2
 [3,]  3    3
 [4,]  4    4
 [5,]  5    5
 [6,]  6    6
 [7,]  7    5
 [8,]  8    4
 [9,]  9    3
[10,] 10    2
[11,] 11    1

1st column is changed. Each element is subtracted by 1. Why?

like image 708
ravi Avatar asked Oct 02 '17 02:10

ravi


People also ask

How do I convert data into a matrix 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.

How do you create a matrix from a table?

To create a matrix, you start with a table and convert it to a matrix. On the Design tab > Switch Visualizations > Table > Matrix.

How do I convert an array to a matrix in R?

To convert an array into a matrix in R, we can use apply function. For example, if we have an array called ARRAY that contains 2 array elements then we can convert this array into a single matrix using the command apply(ARRAY,2,c).


1 Answers

Try matrix instead of as.matrix:

matrix(M, ncol = ncol(M), dimnames = dimnames(M))
like image 53
Jeff Bezos Avatar answered Oct 29 '22 09:10

Jeff Bezos