Understanding the differences in results between dplyr group_by vs tapply

I expected to see the same results between the two runs, and they are different. It makes me wonder if I really understand how dplyr code works (I read almost everything I can find about dplyr in the package and on the Internet). Can someone explain why the results are different, or how to get similar results?

library(dplyr)
x <- iris
x <- x %.%
    group_by(Species, Sepal.Width) %.%
    summarise (freq=n()) %.%
    summarise (mean_by_group = mean(Sepal.Width))  
print(x)

x <- iris
x <- tapply(x$Sepal.Width, x$Species, mean)
print(x)

Update: I don't think this is the most efficient way to do this, but the following code gives a result that is consistent with the tapply approach. At Hadley’s suggestion, I carefully examined the results line by line, and this is the best I could come up with with dplyr

library(dplyr)
x <- iris
x <- x %.%
    group_by(Species, Sepal.Width) %.%
    summarise (freq=n()) %.%
    mutate (mean_by_group = sum(Sepal.Width*freq)/sum(freq)) %.%
print(x)

: - , , , , . , , .

x <- iris %.%
    group_by(Species) %.%
    summarise(Sepal.Width = mean(Sepal.Width))
print(x)
+3
1

, ...

- dplyr:

require(dplyr)

iris %>% group_by(Species) %>% summarise(mean_width = mean(Sepal.Width))

  # Source: local data frame [3 x 2]
  #
  #      Species        mean_width
  # 1     setosa             3.428
  # 2 versicolor             2.770
  # 3  virginica             2.974

- tapply:

tapply(iris$Sepal.Width, iris$Species, mean)

  # setosa versicolor  virginica 
  # 3.428      2.770      2.974 

. tapply() , summarise() :

typeof(tapply(iris$Sepal.Width, iris$Species, mean, simplify=TRUE))

  # [1] "double"

a list :

typeof(tapply(iris$Sepal.Width, iris$Species, mean, simplify=FALSE))

  # [1] "list"

, tapply(), :

tbl_df( 
  data.frame( 
    mean_width = tapply( iris$Sepal.Width, 
                         iris$Species, 
                         mean )))

  # Source: local data frame [3 x 1]
  #
  #            mean_width
  # setosa          3.428
  # versicolor      2.770
  # virginica       2.974

! unique(iris$Species) attribute, df...

+3

All Articles