Monday, 27 May 2013

Creating multiple instances of a cell value in Google Spreadsheet

Creating multiple instances of a cell value in Google Spreadsheet

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

No comments:

Post a Comment