Search code examples
rdplyranalysis

Need help writing a function for summary_table(dplyr::group_by


I am trying to create a function that will minimize the number of times I will have to calculate all of the stats individually (Min, Median, Max, Mean, SD, and NAs). I have included the first two pieces of this large list, and how the list is being used.

  list("Child Age" =
       list("Min" = ~ min(.data$ChildAge,na_rm = TRUE),
            "Median" = ~ median(.data$ChildAge,na_rm = TRUE),
            "Mean ± SD" = ~ qwraps2::mean_sd(.data$ChildAge,na_rm = TRUE),
            "Max" = ~ max(.data$ChildAge,na_rm = TRUE),
            "NA (Not factored in analysis)" =  ~  percent(sum(is.na(.data$ChildAge)) /length(.data$ChildAge))),
      "Child Gender" =
       list("Girl" = ~ qwraps2::n_perc(.data$ChildGender == "Girl", na_rm = TRUE),
            "Boy" = ~ qwraps2::n_perc(.data$ChildGender == "Boy", na_rm = TRUE))
......
by_clinic_demographic <- summary_table(dplyr::group_by(df, Clinic), demographic_summary)
by_clinic_demographic

I have tried to design a function that will work:

analysis_func <- function(x=df$StudyID) {
  list1 <- list("Min" =   min(x,na.rm = TRUE),
            "Median" =  median(x,na.rm = TRUE),
            "Mean &plusmn; SD" =  qwraps2::mean_sd(x,na_rm = TRUE),
            "Max" =  max(x,na.rm = TRUE),
          "NA (Not factored in analysis)" =   percent(sum(is.na(x)) /length(x)))
  #str(list1)
  return(list1)
}

When I then go to call this function in a new list:

assessment_summary <-
  list("Mother Age" = analysis_func(.data$MotherAge),, 

I get the error: Error: x must be a formula

When I add ~ after the = sign, so for example:

"Min" = ~  min(x,na.rm = TRUE)

I then get the error: Error in FUN(X[[i]], ...) : only defined on a data frame with all numeric variables

Here is a simplified version to highlight the issue that I am having:

analysis_func <- function(x=df$StudyID) {
  list1 <- list("Min" = ~ min(x,na.rm = TRUE),
            "Median" = ~ median(x,na.rm = TRUE),
            "Mean &plusmn; SD" = ~ qwraps2::mean_sd(x,na_rm = TRUE),
            "Max" = ~ max(x,na.rm = TRUE),
          "NA (Not factored in analysis)" =  ~ percent(sum(is.na(x)) /length(x)))
  return(list1)
}
test_summary <-
  list("Scores" = analysis_func(.data$StudyID))
# test_stack <- summary_table(dplyr::group_by(dataframe, s), test_summary)
# test_stack

n = c(2, 3, 5, 4,10,12,rep(10,4)) 
s = c(rep("aa",5),rep("bb",5)) 
dataframe <- data.frame (n,s)



test_summary2 <-
  list("Scores" =
       list("Min" = ~ min(.data$n,na_rm = TRUE),
            "Median" = ~ median(.data$n,na_rm = TRUE),
            "Mean &plusmn; SD" = ~ qwraps2::mean_sd(.data$n,na_rm = TRUE),
            "Max" = ~ max(.data$n,na_rm = TRUE),
            "NA (Not factored in analysis)" =  ~  percent(sum(is.na(.data$n)) /length(.data$n)))
  )

test_stack <- summary_table(dplyr::group_by(dataframe, s), test_summary2)
test_stack

Any help would be appreciated.


Solution

  • We can use this function :

    analysis_func <- function(x) {
       list1 <- list(Min = min(x,na.rm = TRUE),
                     Median = median(x,na.rm = TRUE),
                     Mean = mean(x,na.rm = TRUE),
                     SD = sd(x, na.rm = TRUE),
                     Max = max(x,na.rm = TRUE),
                    "NA (Not factored in analysis)" =  mean(is.na(x)))
        return(list(list1))
    }
    

    and then call it by group.

    library(dplyr)
    dataframe %>% group_by(s) %>% summarise(summary_list = analysis_func(n)) 
    
    
    # A tibble: 3 x 2
    #  s     summary_list    
    #  <fct> <list>          
    #1 aa    <named list [6]>
    #2 bb    <named list [6]>
    #3 cc    <named list [6]>
    

    If we want output as separate columns we can add unnest_wider

    dataframe %>%
      group_by(s) %>%
      summarise(summary_list = analysis_func(n))  %>%
      tidyr::unnest_wider(summary_list)
    
    # A tibble: 3 x 7
    #   s       Min Median  Mean    SD   Max `NA (Not factored in analysis)`
    #  <fct> <dbl>  <dbl> <dbl> <dbl> <dbl>                           <dbl>
    #1 aa        2      3     3  1.41     4                               0
    #2 bb        3      3     3 NA        3                               0
    #3 cc        5      5     5 NA        5                               0