how to convert table() to matrix in r

Viewed 19801

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?

3 Answers

Try matrix instead of as.matrix:

matrix(M, ncol = ncol(M), dimnames = dimnames(M))

I finally found the answer.

DF <- data.frame(table(M))
pmfY <- apply(as.matrix.noquote(DF),2,as.numeric)

The output of pmfY is which is exactly same as table(M).

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

After retracing your steps, ...

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

x <- table(M)

we can investigate what happens with …

str(x)
#>  'table' int [1:11(1d)] 1 2 3 4 5 6 5 4 3 2 ...
#>  - attr(*, "dimnames")=List of 1
#>   ..$ M: chr [1:11] "2" "3" "4" "5" ...

As you can see, the elements already are names not values. That is why as.matrix(table(M)) does not give you elements as values in a first column. Names are still names, instead. Knowing this, another solution would be to extract the names and add them as integers to the matrix:

matrix(c(as.integer(names(x)), x), ncol = 2, dimnames = list(NULL, c("M", "Freq")))
#>          M Freq
#>  [1,]    2    1
#>  [2,]    3    2
#>  [3,]    4    3
#>  [4,]    5    4
#>  [5,]    6    5
#>  [6,]    7    6
#>  [7,]    8    5
#>  [8,]    9    4
#>  [9,]   10    3
#> [10,]   11    2
#> [11,]   12    1

Created on 2021-04-23 by the reprex package (v2.0.0)

Related