2

This may be a beginner question but I can't find an answer on the webs... maybe because I'm not good at describing the problem.

I want to create a frequency table of nominal data separate by rows. For example, in this matrix:

x <- matrix(nrow = 3, ncol = 3, 
  c("A","B","B",
  "C","C","B",
 "D","A","B"
  ))

Using the table(x) function gives me:

A B C D
2 4 2 1

But I want to obtain separate counts for each row, where the resulting table is:

A B C D
1 2 0 0

0 1 1 0

1 1 0 1

I'm sure this is some version of a contingency table but for the life of me, I can't figure it out.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
randmlaber
  • 109
  • 1
  • 1
  • 6

1 Answers1

2

We can use apply, with MARGIN=1, to loop through the columns, convert to factor with levels specified as unique elements of 'x', and get the table

un1 <- sort(unique(c(x)))
t(apply(x, 2, function(x) table(factor(x, levels = un1))))
#     A B C D
#[1,] 1 2 0 0
#[2,] 0 1 2 0
#[3,] 1 1 0 1

Or use a vectorized approach

table(c(col(x)), c(x))
#    A B C D
#  1 1 2 0 0
#  2 0 1 2 0
#  3 1 1 0 1
akrun
  • 874,273
  • 37
  • 540
  • 662