不正确地使用ddply来汇总R中的数据

时间:2016-02-14 21:44:48

标签: r plyr

我在执行相当简单的ddply操作时遇到问题:我有以下数据帧。

+----------+----------+
| Expenses | Category |
+----------+----------+
|      735 |        1 |
|      992 |        2 |
|      943 |        1 |
|      995 |        3 |
|      914 |        3 |
|      935 |        1 |
|      956 |        3 |
|      946 |        2 |
|      978 |        1 |
|      924 |        1 |
+----------+----------+

我试图通过执行以下操作来计算每个类别的N和费用平均值:

ddply(df, .(Category), summarise, N = length(df$Expenses), mean = mean(df$Expenses))

然而我得到:

  Category  N  mean
1        1 10 931.8
2        2 10 931.8
3        3 10 931.8

你能帮我找出我在这里做错了吗?

以下是df' dput

structure(list(Expenses = c(735, 992, 943, 995, 914, 935, 956, 
946, 978, 924), Category = c(1L, 2L, 1L, 3L, 3L, 1L, 3L, 2L, 
1L, 1L)), .Names = c("Expenses", "Category"), class = "data.frame", row.names = c(NA, 
-10L))

1 个答案:

答案 0 :(得分:1)

使用dplyr的替代方法:

library(dplyr);

grouped_df    <- group_by(df, Category);
summarized_df <- summarize(grouped_df, N    = n(),
                                       mean = mean(Expenses));
summarized_df;