-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Derived Attributes
The derivedAttributes
parameter to both pivot()
and pivotUI()
can be used to add new attributes to the original data set, derived from the existing ones. This can be useful to make the data more pivot-friendly. This parameter should be a dictionary of functions: the keys are the names of the new attributes, and the functions take an existing record and return the value of the new attribute.
Here is the source for a very simple deriver, which will look for an existing attribute called Age
and return the decade that age belongs to:
var ageBinDeriver = function(record) {
return record.Age - record.Age % 10;
}
Some built-in deriver generators are available under $.pivotUtilities.derivers
As it happens, 'binning' high-cardinality attributes like age into lower-cardinality buckets is a pretty frequent use-case, so PivotTable.js actually provides a helper to do the above:
var ageBinDeriver = $.pivotUtilities.derivers.bin("Age", 10);
Another frequently-encountered use-case is to bin date or date-time values by day, hour, minute, week, month etc, so PivotTable.js provides a helper for that too:
var monthAndDayDeriver = $.pivotUtilities.derivers.dateFormat("Name of Attribute", "%m/%d")
The second parameter interpolates as follows:
- %y: date.getFullYear()
- %m: zeroPad(date.getMonth()+1)
- %n: mthNames[date.getMonth()]
- %d: zeroPad(date.getDate())
- %w: dayNames[date.getDay()]
- %x: date.getDay()
- %H: zeroPad(date.getHours())
- %M: zeroPad(date.getMinutes())
- %S: zeroPad(date.getSeconds())
Remember that PivotTable.js uses a fairly simple natural sort so if you want to pivot across, say, month names (%n) then make sure you include the month number first (i.e. use "%m-%n" as your formatting string) otherwise your months will be sorted alphabetically!
The third parameter to the dateFormat
deriver specifies if the input should be assumed to be in the UTC timezone or not, and it default to false
.
Localization note: The fourth and fifth parameters to the dateFormat
deriver are arrays of locale-specific month and day names, and they default to English values.