Solved

Access -- calculate "median" and "mode"

Posted on 2014-11-26
19
557 Views
Last Modified: 2014-12-02
Experts:

Please find attached two files:  
1. "Example Data -- Statistics" (Excel)
2. "Mean, StDev, Var" (Access)

The Excel file contains the following five stats:
- Mean/Average
- StDev
- Var
- Median
- Mode

I've imported the 10 values (B1:B10) into Table1 of the Access file.   In Query1, the mean, stdev, and variance can be easily derived.

My question:  How can I compute/calculate the **median** and **mode** in the database?  

Note: Please keep in mind that I'm currently (in the actual database) using a SQL statement that re-generates queries for other input.   That said, if VBA is required for the calculation of these two statistical measures of dispersion, I need to be able to "call that function" from within Query1 in order to dynamically create/update other queries.

Ideally, any proposed solution includes a working query1 that includes these two measures.

Thank you for your assistance in advance.
EEH
Example-Data----Statistics.xlsx
Mean--StDev--Var.accdb
0
Comment
Question by:ExpExchHelp
  • 8
  • 6
  • 2
  • +3
19 Comments
 
LVL 119

Expert Comment

by:Rey Obrero
ID: 40467702
0
 
LVL 34

Expert Comment

by:PatHartman
ID: 40467739
Calculate Mode:
SELECT TOP 1 Amt, Count(*) AS Mode
FROM YourTable
GROUP BY Amt
ORDER BY Count(*) DESC, Amt DESC;

This method ignores ties.
0
 

Author Comment

by:ExpExchHelp
ID: 40467789
@Rey:

Thank you for the link... I've read the information.   I wasn't successful calling the function "DMedian" from the query.   I'm sure I did something wrong.    Btw, the link to the sample db isn't working any longer.

@PatHartmann:
Thank you... I was able to calculate the mode in a query (based on your feedback).   Ideally though, based on my requirement for using dynamic SQL statements, is there a way to use the SQL code in a module/function... and then call the function in a query via, e.g., "ModeValue: Mode([LikertValu])?   If yes, how can this be done?

Thank you,
EEH
0
 
LVL 74

Expert Comment

by:Jeffrey Coachman
ID: 40467808
You can also "reference" the Excel Median/Mode function, ...then use code to use this in a function in Access
I have a simple sample file I can upload if you like.
0
 
LVL 61

Expert Comment

by:mbizup
ID: 40467811
There are several EE articles you might want to check out.  Look in the right hand sidebar of this page under "Deeper MS Access Learning".  Patrick Matthews has an article which covers Median and Mode thoroughly with sample code, queries and a sample database:

http://www.experts-exchange.com/Database/MS_Access/A_2529-Median-Mode-Skewness-and-Kurtosis-in-MS-Access.html
0
 

Author Comment

by:ExpExchHelp
ID: 40467824
Jeffrey Coachman -- yes, I definitely would like to view your example.   Thank you in advance for sharing it!

mbizup -- I'll check out the reading material.   Thanks for posting the link.
0
 
LVL 74

Expert Comment

by:Jeffrey Coachman
ID: 40467886
I will see if I can dig up that sample tonight.

In the mean time you can investigate the info that mbizup posted...
0
 

Author Comment

by:ExpExchHelp
ID: 40467918
Will do... thank you, Jeffrey.
0
 
LVL 26

Accepted Solution

by:
Nick67 earned 500 total points
ID: 40468168
Ideally though, based on my requirement for using dynamic SQL statements, is there a way to use the SQL code in a module/function... and then call the function in a query via, e.g., "ModeValue: Mode([LikertValu])?   If yes, how can this be done?

You can create wrapper functions of all kinds, which you can then call in the Query Editor.
These are an especially handy trick if you need to use a global variable in a query
Check to ensure my coding is good -- and I put NULL checks into it, but throw this in a code module
Option Compare Database
Option Explicit

Public Function ModalValue(BaseObjectName As String, FieldName As String) As Single
'BaseObjectName  can be the name of any table or query
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("SELECT TOP 1 " & FieldName & " , Count(*) AS Mode  FROM " & BaseObjectName & " where " & FieldName & " is not null GROUP BY " & FieldName & " ORDER BY Count(*) DESC," & FieldName & " DESC;", dbOpenDynaset, dbSeeChanges)

ModalValue = rs.Fields(FieldName).Value
rs.Close
Set rs = Nothing

End Function


Public Function MedianValue(BaseObjectName As String, FieldName As String) As Single
'BaseObjectName  can be the name of any table or query
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("SELECT " & FieldName & " FROM " & BaseObjectName & " where " & FieldName & " is not null  ORDER BY " & FieldName & ";", dbOpenDynaset, dbSeeChanges)
rs.MoveLast
rs.MoveFirst

'ok if rs.recordcount is odd then things are easy
If rs.RecordCount Mod 2 = 1 Then
    'odd number
    rs.Move ((rs.RecordCount - 1) / 2)
    MedianValue = rs(FieldName)
Else
    rs.Move ((rs.RecordCount - 2) / 2)
    MedianValue = rs(FieldName)
    rs.MoveNext
    MedianValue = MedianValue + rs(FieldName)
    MedianValue = MedianValue / 2
End If
End Function

Open in new window


And you can call them via
ModalValue("SomeTable or Query","SomeField")
=MedianValue("SomeTable or Query","SomeField")

As with PatHartmann's code, ties are ignored
0
U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

 
LVL 26

Expert Comment

by:Nick67
ID: 40468177
@ExpExchHelp
Btw, the link to the sample db isn't working any longer.
EE presently has bug in downloading .accdb files
If you right click them, change the dialog to 'All Files' and rename them to .accdb, they can be downloaded and run.

PITA, and I do have a bug notice in about it.
0
 
LVL 26

Expert Comment

by:Nick67
ID: 40468214
As with PatHartmann's code, ties are ignored

The reason ties are ignored is that
a) a SQL "Select Top 1 ..." is only going to return one value and
b) It's a bit hellish to code

If you have a set 1,2,2,2,3 your mode function can return something numeric, like an integer or a long
If you have a set 1.1, 2.1. 2.2, 2.2, 2.2 ,3.0 you can still return something numeric like a single.
If you allow ties and need them, well
A set like 1,2,2,2,3,3,3,4,4,4,5,5,5,5,6 is going to return --and have to return-- a string like 2,3,4,5
And that's really no fun.

Testing the string, is there more than one element, what's the delimiter, running a Split, coercing the fragments...
Well, you get the idea.
Not a lot of fun, all the way down the line.
0
 

Author Comment

by:ExpExchHelp
ID: 40468236
Nick67:

I think this is an excellent solution... thank you for providing it.

In the test database, all values appear to be computed correctly.   I will integrate your solution into the actual database early next week.   Some of my existing queries do not use the "group by"... so I have to see whether or not this may cause a conflict.  

If I end up w/ a follow-up question, I will post any issues and refer to a new post (i.e., question).  

I'd like to thank everyone for contributing to this solution.   Nick's proposed solution, however, best addresses the requirements.   Again, thanks!!

EEH
0
 

Author Closing Comment

by:ExpExchHelp
ID: 40468238
Excellent solution!!
0
 

Author Comment

by:ExpExchHelp
ID: 40473579
Nick67:

Quick follow-up question.    As part of the dataset, a 5-point Likert scale is used.   For survey respondents who didn't know the answer to a question, a value of 999 is automatically being entered.   That criteria (999 = null) cannot change.

In order to exclude any 999 values (for calculation of average, variance, and standard deviation), I have been using the following expressions in my queries:
Average: Avg(IIf([LikertValue]=999,Null,[LikertValue]))

Based on the module (calculation for median and mode), I've tried to use the sample principle to change the expression for the, e.g., median from/to:

From:
Median: MedianValue("Table1","LikertValue")

To:
Median: IIf(MedianValue("Table1","LikertValue")=999,Null,MedianValue("Table1","LikertValue"))

Unfortunately, that did not work and it still shows, e.g., a median of "502" when using the following sample data:
LikertValue
1
2
2
5
5
999
999
999
999
999

My question:  How can I modify the expression so that the 999 values are excluded from calculating the median and/or mode?

Thanks,
EEH
0
 
LVL 26

Expert Comment

by:Nick67
ID: 40474179
Alter the recordset opening command as appropriate.  This for Mode:
Set rs = CurrentDb.OpenRecordset("SELECT TOP 1 " & FieldName & " , Count(*) AS Mode  FROM " & BaseObjectName & " where " & FieldName & " is not null GROUP BY " & FieldName & " ORDER BY Count(*) DESC," & FieldName & " DESC;", dbOpenDynaset, dbSeeChanges)

We are already excluding Null
Now throw out 999 too

Set rs = CurrentDb.OpenRecordset("SELECT TOP 1 " & FieldName & " , Count(*) AS Mode  FROM " & BaseObjectName & " where " & FieldName & " is not null AND " & FieldName & " <> 999 GROUP BY " & FieldName & " ORDER BY Count(*) DESC," & FieldName & " DESC;", dbOpenDynaset, dbSeeChanges)

This for median
Set rs = CurrentDb.OpenRecordset("SELECT " & FieldName & " FROM " & BaseObjectName & " where " & FieldName & " is not null AND " & FieldName & " <> 999 ORDER BY " & FieldName & ";", dbOpenDynaset, dbSeeChanges)
0
 

Author Comment

by:ExpExchHelp
ID: 40474223
Nick67:

Brilliant!!   I've modified the one for the median first... it now compute "2" in the dataset.   :)


For the mode, I actually realized that I may need to include the '999' values.   Here's why:  As mentioned, '999' is an arbitrary value that stands for "I don't know the answer to the question" (or "N/A").

If the majority of survey respondents chose 999 for a specific answer, then I think I should return the mode as 999.   Do you agree with that assumption?   Or do you think it also should be excluded?

EEH
0
 
LVL 26

Expert Comment

by:Nick67
ID: 40474303
It's your data, and you are the one analyzing it.
The mode function is tricky to use in programming.
We haven't built a mode function that returns data about multi-modal data.
We have told the function to return the same multi-modal result each time (smallest field value of the ties)

2,2,3,3,4,4,5,5 have a mode of 2, 3, 4 and 5
The function returns 2

Does the 999 value say something useful?
Then leave it in for mode

Is it so much higher than the 'real' values that if it were used in a median calculation it would skew the daylights out of the value, then leave it out

You could build functions that count 999 and total records and return the % of 999 in the sample.

It's your call
0
 

Author Comment

by:ExpExchHelp
ID: 40475700
Nick67:

Thank you for the additional feedback... I appreciate it.

999 is used for coding any N/A (or "I don't know the answers) responses.    So, in the event the majority of participants selected this value, having such information (as part of the mode) is of value to us as well.

For the median, I may duplicate the function (obviously renaming function/variable names) and then have "median with N/A" and "median without N/A".  

Either way, your solutions for calculating both median and mode are most elegant.

Cheers,
EEH
0
 
LVL 26

Expert Comment

by:Nick67
ID: 40476431
Glad to be of service

Nick67
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most p…
Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
Basics of query design. Shows you how to construct a simple query by adding tables, perform joins, defining output columns, perform sorting, and apply criteria.
What’s inside an Access Desktop Database. Will look at the basic interface, Navigation Pane (Database Container), Tables, Queries, Forms, Report, Macro’s, and VBA code.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now