Error in sum(count) : invalid 'type' (closure) of argument

Viewed 2700

I have an order table that looks like this:

country_code other_info order_status
FR           1523       okay
FR           5151       not_okay
FR           41511      not_okay
IE           5151       okay

Both columns are of class character but even when transforming them into factors I got the same issue.

I just want to have the proportions of order_status grouped by country_code.

After running the following code I've got this error and I really cannot figure out what it means:

'Error in sum(count) : invalid 'type' (closure) of argument 
library(dplyr)
orders %>%
  group_by(country_code) %>%
  mutate(countT= sum(count)) %>%
  group_by(order_status, add=TRUE) %>%
  mutate(per=paste0(round(100*count/countT,2),'%'))

What I want is this:

country_code order_status per
FR           okay         33%
FR           not_okay     66%
IE           okay         100%

Thank you very much for your help, I'm sure it's something not complicated.

1 Answers

In the OP's dataset, there is no 'count' column. If we need to create a column of frequency, then either use n() in mutate after grouping by 'country_code' or directly add_count

library(dplyr)
library(stringr)
order %>%
     add_count(country_code) %>% # create a column with name 'n'
     group_by(country_code, order_status) %>% # grouped by two columns
     mutate(per = str_c(round(100 * n()/n, 2), '%')) # do the rest of computation
# A tibble: 3 x 4
# Groups:   country_code, order_status [3]
#  country_code order_status     n per  
#  <chr>        <chr>        <int> <chr>
#1 FR           okay             2 50%  
#2 FR           not_okay         2 50%  
#3 IE           okay             1 100% 

Or if we need a single row, use summarise

order %>%
     add_count(country_code) %>% # create a column with name 'n'
     group_by(country_code, order_status) %>% # grouped by two columns
     summarise(per = str_c(round(100 * n()/first(n), 2), '%')) 

If we want to get summarised output, change the mutate to summarise

data

order <- structure(list(country_code = c("FR", "FR", "IE"), order_status = c("okay", 
"not_okay", "okay")), class = "data.frame", row.names = c(NA, 
-3L))
Related