Summarising by a group variable in r

后端 未结 2 1890
广开言路
广开言路 2021-01-27 05:22

I have a data frame as follows:

 head(newStormObject)
     FATALITIES   INJURIES    PROPVALDMG CROPVALDMG      EVTYPE     total
 1           0          15    2.5         


        
2条回答
  •  不思量自难忘°
    2021-01-27 05:45

    We can take the first value for all the other columns using slice after updating the 'total' with the sum of 'total'.

    library(dplyr)
    df1 %>% 
       group_by(EVTYPE) %>% 
       mutate(total = sum(total)) %>%
       slice(1L) %>%
       arrange(desc(total))
    #      FATALITIES INJURIES PROPVALDMG CROPVALDMG    EVTYPE total
    #                             
    #1          0       15     250000          0   TORNADO    21
    #2          0        0          0          0      HAIL    12
    #3          0        0          0          0 TSTM WIND     1
    

    NOTE: The 'total' for 'EVTYPE' "HAIL" is 12 based on the example

提交回复
热议问题