dplyr group by multiple variables summarise by multiple variables

拜拜、爱过 提交于 2019-12-11 17:05:39

问题


New to R. Using dplyr, trying to group_by multiple variables, summarize by multiple variables, multiple functions.

This works as expected

mtcars %>% 
+     group_by(cyl,hp) %>% 
+     summarise(min_mpg = min(mpg) , min_disp = min(disp), max_mpg = max(mpg) , max_disp = max(disp))

But when I try to replicate with my df

vmp %>% 
    +     group_by(Priority,LOS) %>% 
    +     summarise(inv_total = sum(Inv_Total), sr_count = count(SR_Nmbr))

I receive this error:

Error in summarise_impl(.data, dots) : Evaluation error: no applicable method for 'groups' applied to an object of class "factor".

What am I doing wrong? Thx


回答1:


library(dplyr)
vmp %>%
     mutate(Inv_Total=as.numeric(as.character(Inv_Total))) %>% 
     group_by(Priority,LOS) %>%
     summarise(sr_count=n(), 
               inv_total=sum(Inv_Total))



回答2:


We can use type.convert to convert the column types automatically

vmp %>%
    mutate_all(funs(type.convert(as.character(.), as.is = TRUE))) %>%
    group_by(Priority, LOS) %>%
    summarise(inv_total = sum(Inv_Total), sr_count =n())


来源:https://stackoverflow.com/questions/45627666/dplyr-group-by-multiple-variables-summarise-by-multiple-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!