2

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) {
    return;
  }

  var instances = [];

  for(var i = 0; i < numberOfInstances; i++) {
    instances.push(instanceValue);
  }

  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"?

1

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

Code

function myMedian(instances, values) {
  var ins = [], half;
  for(var i = 0, iLen = instances.length; i < iLen; i++) {
    for(var k = 0, kLen = instances[i]; k < kLen; k++) {
      ins.push(Number(values[i]));
    }
  }

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

  return ins.length % 2 ? ins[half] : (ins[half - 1] + ins[half]) / 2;
}

Screenshot

enter image description here

Example

See example file I prepared: Median calculation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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