Reputation: 11
I have the following matrix in R
b = matrix(c(1,1,1,1,1,1,1,1,1,1,1,1,2), ncol = 1)
I execute the following command to count all of the unique values.
table(b)
I actually want to know what command I should execute to get a column with all of the values and next to it a column with the count of each value as follows.
[,1] [,2]
[1,] 1 12
[2,] 1 12
[3,] 1 12
[4,] 1 12
[5,] 1 12
[6,] 1 12
[7,] 1 12
[8,] 1 12
[9,] 1 12
[10,] 1 12
[11,] 1 12
[12,] 1 12
[13,] 2 1
Upvotes: 1
Views: 70
Reputation: 887881
We can use ave
cbind(b, ave(b[,1], b[,1], FUN=length))
# [,1] [,2]
# [1,] 1 12
# [2,] 1 12
# [3,] 1 12
# [4,] 1 12
# [5,] 1 12
# [6,] 1 12
# [7,] 1 12
# [8,] 1 12
# [9,] 1 12
#[10,] 1 12
#[11,] 1 12
#[12,] 1 12
#[13,] 2 1
Upvotes: 5