Rob
Rob

Reputation: 31

how to calculate a new column after grouping with dplyr

I need to calculate Revenue per load, after grouping by "Team" for my Shiny Dashboard. I am being told I have an invalid 'type' (character) of argument

I have tried changing how the summarise function is formatted. It does not work in the console, so I have removed the Shiny portions of the code.

 August <- data.frame("Revenue" = c(10,20,30,40), "Volume" = c(2,4,5,7), 
 "Team" = c("Blue","Green","Gold","Purple"))


  x <-   August %>% group_by(Team) %>% summarise(Revenue = sum(Revenue)) / 
 August %>% group_by(Team) %>% summarise(Volume = sum(volume)) %>%

"Error: invalid 'type' (character) of argument" this shows up instead of the bar graph

Upvotes: 0

Views: 118

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269596

Summarize the Revenue and Volume and then take their ratio. Note that summarise proceeds from left to right so that after Revenue and Volume have been defined in the summarise statement the references in the RevByVol definition to them refers to these new definitions and not to the original unsummarized versions.

August %>% 
  group_by(Team) %>% 
  summarise(Revenue = sum(Revenue), 
    Volume = sum(Volume), 
    RevByVol = Revenue / Volume) %>%
  ungroup 

giving:

# A tibble: 4 x 4
  Team   Revenue Volume RevByVol
  <fct>    <dbl>  <dbl>    <dbl>
1 Blue        10      2     5   
2 Gold        30      5     6   
3 Green       20      4     5   
4 Purple      40      7     5.71

Upvotes: 1

Related Questions