-3

Have a 1000*16 matrix from a simulation with team names as characters. I want to count number of occurrences per team in all 16 columns.

I know I could do apply(test, 2, table) but that makes the data hard to work with afterward since all teams is not included in every column.

SuchARush
  • 31
  • 5

1 Answers1

0

If you have a vector that is all the unique team names you could do something like this. I'm counting occurrences here via column to ensure that not every team (in this case letter) is not included.

set.seed(15)

letter_mat <- matrix(
  sample(
    LETTERS,
    size = 1000*16,
    replace = TRUE
  ),
  ncol = 16,
  nrow = 1000
)

output <- t(
  apply(
    letter_mat,
    1,
    function(x) table(factor(x, levels = LETTERS))
  )
)

head(output)

     A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
[1,] 1 2 0 1 1 1 1 0 0 0 1 0 0 0 0 1 1 1 1 1 0 1 1 0 0 1
[2,] 0 1 0 2 2 1 0 1 0 0 0 0 0 1 0 0 0 0 0 1 1 1 0 2 2 1
[3,] 1 1 0 0 1 0 1 2 1 0 0 0 0 0 1 0 1 0 1 1 0 0 3 0 1 1
[4,] 0 1 0 0 0 1 0 0 0 2 0 1 0 0 1 1 1 1 2 0 2 3 0 0 0 0
[5,] 2 1 0 0 0 0 0 2 0 2 1 1 1 0 0 2 0 2 1 0 0 1 0 0 0 0
[6,] 0 0 0 0 0 1 3 1 0 0 0 0 1 1 3 0 1 0 0 1 0 0 0 1 0 3

mfidino
  • 3,030
  • 1
  • 9
  • 13