Reputation: 95
Let's say I have the following in 12x3 matrix
m<-rbind(c(0,7,0),c(1,1,5),c(6,1,1),c(1,3,-3),c(1,3,-3),c(1,1,5),
c(0,7,0),c(1,1,5),c(1,1,5),-c(0,7,0),c(1,1,5),c(1,3,-3))
and would like count the number of times each row-vector occurs. What do I do?
I have tried to use table()
, but table()
only counts the elements.
Upvotes: 4
Views: 307
Reputation: 193667
Here's an alternative that keeps the source data as columns. It uses the .N
function from "data.table":
library(data.table)
as.data.table(m)[, .N, by = eval(paste0("V", seq_len(ncol(m))))]
# V1 V2 V3 N
# 1: 0 7 0 2
# 2: 1 1 5 5
# 3: 6 1 1 1
# 4: 1 3 -3 3
# 5: 0 -7 0 1
Upvotes: 2
Reputation: 887691
Or convert to data.frame
and use do.call(paste
table(do.call(paste, as.data.frame(m)))
#0 -7 0 0 7 0 1 1 5 1 3 -3 6 1 1
# 1 2 5 3 1
Or use sprintf
table(do.call(sprintf, c(as.data.frame(m), '%d %d %d')))
Upvotes: 1
Reputation: 19970
You could convert each row to a concatenated string and then use table.
m <- apply(m, 1, function(x) paste(x, collapse=" "))
table(m)
m
0 -7 0 0 7 0 1 1 5 1 3 -3 6 1 1
1 2 5 3 1
Upvotes: 4