simone - 5 months ago 39

R Question

I have a matrix that looks like this

mymat

`A B C D E F`

9 9 9 9 9 9

1 1 1 6 1 6

1 1 1 6 1 9

1 1 1 6 1 9

1 1 1 6 1 6

I want to count occurrences of each number by column, and write a separate matrix such as

`n1 n6 n9`

4 0 1

4 0 1

4 0 1

0 4 1

4 0 1

0 2 3

Where each row represents occurrences of the respective column. I managed to count occurrences by column using

`require(plyr)`

apply(mymat,2,count)

But I obtain a list of data frame with occurrences rather that one matrix. Any help would be much appreciated

Answer

You can try this:

```
table(col(mymat), mymat)
# mymat
# 1 6 9
# 1 4 0 1
# 2 4 0 1
# 3 4 0 1
# 4 0 4 1
# 5 4 0 1
# 6 0 2 3
```

where `col`

gives the column index for each element in the matrix, and a count of the element grouped by the column index can be calculated with the `table()`

function.