Take the 2-minute tour ×
Web Applications Stack Exchange is a question and answer site for power users of web applications. It's 100% free, no registration required.

I have a Google Spreadsheet with the following data:

            A               B
1 | Number of responses | Value
2 |         1               1
3 |         3               2
4 |         0               3

Based on this data, I'd like to calculate the median response. The median in this case is obviously 2, since the responses are (1, 2, 2, 2). But how to do this calculation in Google Spreadsheets, preferably in an elegant way?

The best I've come up with is to write a custom function (Tools -> Script Editor):

* Returns an array with the specified number of instances with the given
* instanceValue.
function multipleInstances(numberOfInstances, instanceValue) {
  if (numberOfInstances == 0) {

  var instances = [];

  for(var i = 0; i < numberOfInstances; i++) {

  return instances;

Then I've invoked the function to calculate the median:

=MEDIAN(multipleInstances(A2, B2), multipleInstances(A3, B3), multipleInstances(A4, B4))

This works, but is a bit cumbersome. Is there a more elegant way of saying "give me N instances of the value in this cell"?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

The following little script will calculate the median at the same time:

function myMedian(rangeInstances, rangeValues) {
  var instances = [];
  for(var i=0; i<rangeInstances.length; i++) {
    for(var k=0; k<rangeInstances[i]; k++) {

  // reference: https://gist.github.com/caseyjustus/1166258
  instances.sort( function(a,b) {return a - b;} );
  var half = Math.floor(instances.length/2);

  if(instances.length % 2) {
    return instances[half];
  } else {
    return (instances[half-1] + instances[half]) / 2.0;

See example file I prepared: Median calculation

share|improve this answer
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.