sym Invalid Argument Type

Viewed 437

I am trying to add total row after calculating count and proportion. I have created a function for the same but it's returning error when passing !!sym(group_var)

freq_table <- function(df, group_var) {
      
      group_var2 <- !!sym(group_var)
      
      df %>%
        group_by_at(group_var) %>%
        summarise(n = n()) %>%
        mutate(freq = n / sum(n)) %>%
        ungroup %>%
        bind_rows(., data.frame(
          group_var2 := "Grand Total",
          sapply(. %>% dplyr::select_if(is.numeric),
                 function(x) sum(x, na.rm = T)) %>% t()
        ))
      
    }
    
    freq_table(iris, group_var = "Species")
1 Answers

We could do this more easily with adorn_totals

freq_table <- function(df, group_var) {
  df %>%
     dplyr::group_by(across(all_of(group_var))) %>%
     dplyr::summarise(n = n(), .groups = 'drop') %>%
     dplyr::mutate(freq = n / sum(n)) %>%
     janitor::adorn_totals(name = "Grand Total")     
  
}

-testing

freq_table(iris, group_var = "Species")
#     Species   n      freq
#      setosa  50 0.3333333
#  versicolor  50 0.3333333
#   virginica  50 0.3333333
# Grand Total 150 1.0000000

The !! should be used within the tidyverse functions. Also, here we don't need the sym or !! as the OP is using group_by_at which can take a string, then the assignment (:=), the lhs can be string. Modified the bind_rows with the looping by sapply and transpose as this returns a matrix. We can make use of summarise with across to loop over the numeric columns, and add a new row at the bottom with add_row

freq_table <- function(df, group_var) {     
  
    df %>%
       group_by_at(all_of(group_var)) %>%
       summarise(n = n()) %>%
       mutate(freq = n / sum(n)) %>%
       ungroup %>%
       add_row(
      !!group_var := "Grand Total",
                  {.} %>% 
            summarise(across(where(is.numeric), sum, na.rm = TRUE)))          
  
  }

-testing

freq_table(iris, group_var = "Species")
# A tibble: 4 x 3
#  Species         n  freq
#  <chr>       <int> <dbl>
#1 setosa         50 0.333
#2 versicolor     50 0.333
#3 virginica      50 0.333
#4 Grand Total   150 1    
    
Related