Lau99
Lau99

Reputation: 35

Count in plyr not working, returns "wrong result size (3), expected 8 or 1"

Sorry, I know there are lots of 'count' questions already - I'm trying to to return the frequency of occurrence of unique rows a data frame. I'm found lots of solutions suggesting 'count' in the plyr package, but I can't find anything with this error. I've trying to reproduce an example given in another question:

> 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 this returns the following error:

Error: wrong result size (3), expected 8 or 1

I get the same thing with my own data. I've also tried a different example:

> bevs <- data.frame(cbind(name = c("Bill", "Llib"), drink = c("coffee", "tea", "cocoa", "water"), cost = seq(1:8)))
> bevs$cost <- as.integer(bevs$cost)
> bevs

name  drink cost
1 Bill coffee    1
2 Llib    tea    2
3 Bill  cocoa    3
4 Llib  water    4
5 Bill coffee    5
6 Llib    tea    6
7 Bill  cocoa    7
8 Llib  water    8

> count(bevs, "name")

this just returns the number of rows, not the number of unique rows per name.

Source: local data frame [1 x 2]

"name"     n
(chr) (int)
1   name     8 

I'm copying the example code exactly, so I'm not sure what's going on......any help would be appreciated!

Thanks

Upvotes: 2

Views: 2183

Answers (2)

Steven Beaupr&#233;
Steven Beaupr&#233;

Reputation: 21641

An alternative using dplyr:

df %>% count_(names(.)) or df %>% count(x1, x2, x3)

Which gives:

#Source: local data frame [6 x 4]
#Groups: x1, x2 [?]
#
#     x1    x2    x3     n
#  (dbl) (dbl) (dbl) (int)
#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

Upvotes: 1

Vincent Bonhomme
Vincent Bonhomme

Reputation: 7453

I think you've loaded dplyr after plyr (more there). Try the following: plyr::count(df, vars = c("x1", "x2", "x3")) and plyr::count(bevs, "name").

Upvotes: 2

Related Questions