Search code examples
rvariablesmode

Multiple Modes by variables


I can't seem to find an answer for my problem.

Here is sample data

Credit Card Type  Bank   Year   Total Balance
MASTER CARD       BOFA   2017   $100
MASTER CARD       BOFA   2017   $100
MASTER CARD       BOFA   2017   $700
VISA              Wells  2018   $60 
VISA              Wells  2018   $50
VISA              Wells  2018   $60

etc

I am trying to figure how to get a mode by total Balance across all variables So it will end up like this

Desired output:

Credit Card Type  Bank   Year   Mode
MASTER CARD       BOFA   2017   $100
VISA              Wells  2018   $60

Solution

  • From this question obtaining 3 most common elements of groups, concatenating ties, and ignoring less common values

    library(plyr)
    getmode<- function(origtable,groupby,columnname) {
      data <- ddply (origtable, groupby, .fun = function(xx){
        c(m1 = paste(names(sort(table(xx[,columnname]),decreasing=TRUE)[1]))
        ) } ) 
      return(data)
    }
    
    getmode(df,c("CreditCardType","Bank","Year"),"TotalBalance")
    
    df<-read.table(text="CreditCardType  Bank   Year   TotalBalance
    MASTERCARD       BOFA   2017   $100
    MASTERCARD       BOFA   2017   $100
    MASTERCARD       BOFA   2017   $700
    VISA              Wells  2018   $60 
    VISA              Wells  2018   $50
    VISA              Wells  2018   $60", header=T, stringsAsFactors=F)