# Calculating Median and Mode of numerical variables for different subgroups in R

I have customer call data and I want to get the median and mode for the call success rate for different subgroups.

My variables are: Customer ID, Employment Status (Retired, Employed, Unemployed), count of calls, count of successful calls, call success rate (successful calls/number of calls) So far I worked in Excel to get the average call reachability. Mode and median are not easy to calculate with Excel, because it can only do it for up to 255 recods I believe. I know that the summary command in R provides you with summary statistics for each variable but what if you want to get the median and mode of each subgroup. Meaning: Median and Mode of call succcess rate for Retired, Employed and Unemployed customers separately? Why I want to calculate the Median and Mode, although I have the average already? Because both are more resistant to outliers. But I am open for discussion if you think it is not necessary :)

assuming your data is stored in an object named df you can do:

tapply(df$$S_Calls, df$$Emp_Stat, median)


As for the mode, oddly enough R does not have a built in function for that. You could define one yourself using:

mode_stat <- function(x) {
ux <- na.omit(unique(x))
ux[which.max(tabulate(match(x, ux)))]
}


and then do in a similar fashion:

tapply(df$$S_Calls, df$$Emp_Stat, mode_stat)


Since you mentioned that you have the data in excel, first import it in R:

df <- readxl::excel_sheets(path = "file.xlsx")


then calculate median per Emp_Stat:

sapply(unique(df$Emp_Stat), function(x){ sapply(df[df$Emp_Stat == x, ], median)
})


and for mode:

# for every Emp_Stat
sapply(unique(df$Emp_Stat), function(x1){ # for every column sapply(df[df$Emp_Stat == x1, ], function(x2){
which.max(table(x2))
})
})


Ps. What I mentioned and the answer Iyar Lin provided are essentially the same, just using different functions.