How to get the mode of a group in summarize in R

后端 未结 2 1668
情话喂你
情话喂你 2021-01-05 01:50

I want to compare costs of CPT codes from two different claims payers. Both have par and non par priced providers. I am using dplyr and modeest::mlv

2条回答
  •  灰色年华
    2021-01-05 01:55

    I use this approach:

    df <- data.frame(groups = c("A", "A", "A", "B", "B", "C", "C", "C", "D"), nums = c("1", "2", "1", "2", "3", "4", "5", "5", "1"))
    

    which looks like:

     groups nums
      A    1
      A    2
      A    1
      B    2
      B    3
      C    4
      C    5
      C    5
      D    1
    

    Then I define:

    mode <- function(codes){
      which.max(tabulate(codes))
    }
    

    and do the following:

    mds <- df %>%
      group_by(groups) %>%
      summarise(mode = mode(nums))
    

    giving:

      groups  mode
     A          1
     B          2
     C          5
     D          1
    

提交回复
热议问题