9
$\begingroup$

Suppose I have a data frame such like:

df<-data.frame(x1=c(0,1,1,1,2,3,3,3),
x2=c(0,1,1,3,2,3,3,2),
x3=c(0,1,1,1,2,3,3,2))
df
  x1 x2 x3
1  0  0  0
2  1  1  1
3  1  1  1
4  1  3  1
5  2  2  2
6  3  3  3
7  3  3  3
8  3  2  2

what I want is to count the number of each unique row such like:

  x1 x2 x3 count
1  0  0  0  1
2  1  1  1  2
4  1  3  1  1
5  2  2  2  1 
6  3  3  3  2
8  3  2  2  1

What's the easiest way to realize it in R?

$\endgroup$
3
  • $\begingroup$ @Whuber, instead of putting it on hold, just migrate it to SO. It is a reasonable, well formatted and clear question asked on a wrong SE site. We can provide many other good answers there which future users can benefit from. $\endgroup$ Commented Oct 23, 2014 at 11:43
  • $\begingroup$ @David A Thank you for the suggestion. I think you're right, but at the time (a) I saw there was an answer here and (b) I strongly suspected this very question has appeared on SO before. $\endgroup$
    – whuber
    Commented Oct 23, 2014 at 16:24
  • 1
    $\begingroup$ @whuber, I didn't check for dupes, but I think the OP would still receive many more good answers. Either way, it seems they are good with plyr so that doesn't matter anymore I guess. $\endgroup$ Commented Oct 23, 2014 at 20:49

1 Answer 1

16
$\begingroup$

Use the count function from the plyr package.

library(plyr)
df = data.frame(x1=c(0,1,1,1,2,3,3,3),
               x2=c(0,1,1,3,2,3,3,2),
               x3=c(0,1,1,1,2,3,3,2))

count(df, vars = c("x1", "x2", "x3"))

Output:

> count(df, vars = c("x1", "x2", "x3"))
  x1 x2 x3 freq
1  0  0  0    1
2  1  1  1    2
3  1  3  1    1
4  2  2  2    1
5  3  2  2    1
6  3  3  3    2
$\endgroup$
1
  • 1
    $\begingroup$ I copied and pasted your code. I got: "Error in mutate_impl(.data, dots) : Column vars must be length 8 (the number of rows) or one, not 3" $\endgroup$ Commented Nov 16, 2018 at 20:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.