I have a list of tables that I need to make using different variables, and I want to make a function that will let me make the tables differently each time by passing through different variables as arguments. There are many table outputs that need to be made, so I want to summarize the function I'm using to save on lines of code and general sanity (to my own insanity of learning function creation in tidyverse).
I am getting several different kinds of errors based on how I run the code, but the most consistent form I've run it is giving me:
Error in `dplyr::summarise()`:
! Problem while computing `Number of
vets with at least 11 patients =
sum(...)`.
i The error occurred in group 1: site =
"site1".
"Caused by error in `ifelse()`:
! unused arguments (condition = (~vars(var1)) >= 11, true = ~vars(var2), false = 0)"
Here's what I tried and what I was expecting to generate:
I have a dataset with many other variables but for example:
site | var1 | var2 | etc |
---|---|---|---|
site1 | 3 | 3 | 3 |
site2 | 66 | 65 | 64 |
site2 | 23 | 45 | 34 |
site2 | 45 | 48 | 49 |
site3 | 542 | 423 | 543 |
site3 | 68 | 63 | 678 |
make_vet_site_table_row <- function(df, var1, var2) {
df %>% dplyr::summarise(
"Total number of vets" = n(),
"Number of customers with at least 11 dogs" = sum(ifelse(condition = {{var1}}>=11, true = {{var2}}, false = 0)),
"Number of customers with at least 20 dogs" = sum(ifelse(condition = {{var1}}>=20, true = {{var2}}, false = 0)),
"Total number of dogs" = sum({{var1}}),
"Mean number of patients (by vet)" = round(mean({{var1}}), digits = 2),
"Range of the number of patients (by vet)" = max({{var1}})- min({{var1}}),
"Smallest and largest number of dogs (by vet)" = paste0(min({{var1}}), ", ", max({{var1}}))
)}
df.vetsite.2021 <- df.vetqm %>% filter(year=="2021" & var1_final_denom>0) %>% group_by(site)
#Here's what I want to be able to do from the function:
df.vetsite1.2021 %>% make_vet_site_table_row( var1 = vars(var1_final_denom), var2 = vars(var2_for_cnt))
df.vetsite2.2021 %>% make_vet_site_table_row( var1 = vars(var1_beginning_denom), var2 = vars(var2_for_cnt))
what I want is a table:
site | Total number of clinicians | Number of clinicians with at least 11 patients | etc. |
---|---|---|---|
site 1 | 81 | 54 | -------- |
site 2 | 49 | 0 | -------- |
site 3 | 49 | 0 | -------- |