【发布时间】:2016-09-25 17:24:36
【问题描述】:
我有这个data.frame:
df_test = structure(list(`MAE %` = c(-0.0647202646339709, -0.126867775585001,
-1.81159420289855, -1.03092783505155, -2.0375491194877, -0.160783192796913,
-0.585827216261999, -0.052988554472234, -0.703351261894911, -0.902996305924203,
-0.767676767676768, -0.0101091791346543, -0.0134480903711673,
-0.229357798165138, -0.176407935028625, -0.627062706270627, -1.75706139769261,
-1.23024009524439, -0.257391763463569, -0.878347259688137, -0.123613523987705,
-1.65711947626841, -2.11718534838887, -0.256285931980328, -1.87152777777778,
-0.0552333609500138, -0.943983402489627, -0.541095890410959,
-0.118607409474639, -0.840453845076341), Profit = c(7260, 2160,
-7080, 3600, -8700, 6300, -540, 10680, -1880, -3560, -720, 5400,
5280, 1800, 11040, -240, -2320, 2520, 10300, -2520, 8400, -9240,
-5190, 7350, -6790, 3600, -3240, 8640, 7150, -2400)), .Names = c("MAE %",
"Profit"), row.names = c(NA, 30L), class = "data.frame")
现在我想要一些汇总统计数据,例如:
df_test %>%
group_by(win.g = Profit > 0) %>%
summarise(GroupCnt = n(),
TopMAE = filter(`MAE %` > -1) %>% sum(Profit),
BottomMAE = filter(`MAE %` <= -1) %>% sum(Profit))
因此,如果利润 > 0 或 -1 的行的利润 sum()。 TopMAE、BottomMAE计算必须使用分组。
预期结果如下:
# win.g CroupCnt TopMAE BottomMAE
#1 FALSE 14 -15100 -39320
#2 TRUE 16 95360 6120
但是我的 R 代码不起作用。我有一个错误:
错误:没有适用于“过滤器”的方法应用于“逻辑”类的对象
我已根据错误更改了我的代码:
df_test %>%
group_by(win.g = Profit > 0) %>%
summarise(UnderStop = n(),
TopMAE = filter(., `MAE %` > -1) %>% sum(Profit),
BottomMAE = filter(., `MAE %` <= -1) %>% sum(Profit))
但结果是没有。我又报错了:
错误:长度不正确 (14),预期:16
我试图了解分组行为以及如何在分组后在汇总中使用管道,但我没有成功。花一整天的时间。
如何获得我的预期结果表?在对这些组进行分组和计算某些函数时,请帮助我理解 dplyr 逻辑。
【问题讨论】:
标签: r group-by pipe dplyr summary