Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R table by matrix row

Tags:

r

matrix

For a matrix (as.matrix), how can I generate a table where rows are equal to rows of the matrix?

>table(matrix)

and

>hist(matrix)

show the cumulative sum for each unique data value in the matrix, but I would like a table where rows are the same value as each matrix row, and table columns are the sum occurrence of each unique data value in the matrix.

Example matrix:

   1  2  3  4 
a  5  5  4  6    
b  5  5  5  5     
c  8  7  6  6   
d  2  6  6  6     
e  7  7  5  4      

Desired output table:

   2  4  5  6  7  8
a  0  1  2  1  0  0
b  0  0  4  0  0  0
c  0  0  0  2  1  1
d  1  0  0  3  0  0
e  0  1  1  0  2  0
like image 361
TallTree Avatar asked Apr 28 '13 04:04

TallTree


People also ask

What is the difference between a matrix and data frame in R?

In a data frame the columns contain different types of data, but in a matrix all the elements are the same type of data. A matrix in R is like a mathematical matrix, containing all the same type of thing (usually numbers). R often but not always lets these be used interchangably.

How do you access the matrix element in R?

Accessing Elements of a Matrix Elements of a matrix can be accessed by using the column and row index of the element.

What does prop table do in R?

The prop. table() function in R can be used to calculate the value of each cell in a table as a proportion of all values.


1 Answers

One alternative is to convert your matrix to a long data.frame (using stack), at which point you can easily use table:

Here's your data:

mymat <- structure(c(5L, 5L, 8L, 2L, 7L, 5L, 5L, 7L, 6L, 7L, 4L, 5L, 6L, 
            6L, 5L, 6L, 5L, 6L, 6L, 4L), .Dim = c(5L, 4L), .Dimnames = list(
              c("a", "b", "c", "d", "e"), c("1", "2", "3", "4")))

This is what it looks like as a long data.frame:

head(stack(data.frame(t(mymat))))
#   values ind
# 1      5   a
# 2      5   a
# 3      4   a
# 4      6   a
# 5      5   b
# 6      5   b

Here's how we can use that to create the table you want:

with(stack(data.frame(t(mymat))), table(ind, values))
#    values
# ind 2 4 5 6 7 8
#   a 0 1 2 1 0 0
#   b 0 0 4 0 0 0
#   c 0 0 0 2 1 1
#   d 1 0 0 3 0 0
#   e 0 1 1 0 2 0
like image 101
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 16 '22 01:11

A5C1D2H2I1M1N2O1R2T1