0

This was asked on CrossValidated, but the answer does not seem to be compatible with more recent versions of R.

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?

The answer was:

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"))

But when I use that, I get:

Error in mutate_impl(.data, dots) : 
  Column `vars` must be length 8 (the number of rows) or one, not 3

How can I get the number of times each row appears in the data frame?

StatsSorceress
  • 3,019
  • 7
  • 41
  • 82
  • 1
    Try `plyr::count(df, vars = c("x1", "x2", "x3"))` it seems to be a package conflict. – markus Nov 16 '18 at 20:25
  • It works fine for me. Did you copy the code exactly as above? That error message looks like you might have loaded `dplyr` instead of or after `plyr`. They both have `count()` functions which are incompatible. – MrFlick Nov 16 '18 at 20:25
  • I followed the link from Henrik, and modified the answer there: library(dplyr) answer <- my_df %>% add_count(col1name, col2name) – StatsSorceress Nov 16 '18 at 20:38

0 Answers0