按组汇总所有列 [英] Summing all columns by group

查看:61
本文介绍了按组汇总所有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很肯定这是一个非常简单的答案,但我似乎无法在多种条件下进行汇总或投射

I'm positive that this is an incredibly easy answer but I can't seem to get my head around aggregating or casting with Multiple conditions

我有一张桌子看起来像这样:

I have a table that looks like this:

> head(df, n=10L)
   STATE  EVTYPE FATALITIES INJURIES
1     AL TORNADO          0       15
3     AL TORNADO          0        2
4     AL TORNADO          0        2
5     AL TORNADO          0        2
6     AL TORNADO          0        6
7     AL TORNADO          0        1
9     AL TORNADO          1       14
11    AL TORNADO          0        3
12    AL TORNADO          0        3
13    AL TORNADO          1       26

显然,这种情况还在继续……我要做的就是崩溃按照STATE和EVTYPE的方法,我正在总结死亡和伤害,因此,如果这10行是我的有效数据集,那么结果将是一个单行数据帧:

Obviously this goes on... What I want to do is to collapse by STATE and EVTYPE Summing Fatalities and Injuries as I go so if these 10 rows were my ful dataset the result would be a single row data frame of:

   STATE  EVTYPE FATALITIES INJURIES
1     AL TORNADO          2       74

我的完整画面有很多州和很多EVTYPES

My Complete frame has many States and many EVTYPES

推荐答案

您可以尝试

library(dplyr)
df %>% 
    group_by(STATE, EVTYPE) %>% 
    summarise_each(funs(sum))

aggregate(.~STATE+EVTYPE, df, sum)

这篇关于按组汇总所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆