Grouping age data into 5 year bins
Show older comments
Dear MATLAB experts,
I'm trying to create a new column in a table, which contains the age binned into 5 years intervals per row. This column should create the age bins according to another column in the same table, which specifies the age of the individual per row. In order to make what I'm looking for more clear, here a few examples:
If the age of the individual in a certain row were 25.92 (in the age column), the binned age column should display the following value: (25.0, 30.0]
If the age of the individual in a certain row were 42.53 (in the age column), the binned age column should display the following value: (40.0, 45.0]
If the age of the individual in a certain row were 33 (in the age column), the binned age column should display the following value: (30.0, 35.0]
... and so on
Thank you in advance
Accepted Answer
More Answers (1)
J. Alex Lee
on 12 May 2021
Edited: J. Alex Lee
on 12 May 2021
Interesting, this could be useful for me too! You can use "discretize" to bin the data. Below is a quick and dirty class to implement this idea.
BinEdges = 20:5:45
Data = [25.92;42.53;33;30]
% make sure discretize does what i want
[BData,E] = discretize(Data,BinEdges,"IncludedEdge","right")
LeftEdges = BinEdges(BData)
RightEdges = BinEdges(BData+1)
Using the class below results in:
>> db = DataBins(BinEdges,Data)
db =
"[25,30)"
"[40,45)"
"[30,35)"
"[30,35)"
>> db.IncludedEdge = "right"
db =
"(25,30]"
"(40,45]"
"(30,35]"
"(25,30]"
The class
classdef DataBins < handle & matlab.mixin.CustomDisplay
properties
BinEdges
IncludedEdge
Value
BinIDs
LeftEdges
RightEdges
end
methods
function this = DataBins(BinEdges,Value,IncludedEdge)
arguments
BinEdges (1,:)
Value
IncludedEdge (1,1) string {mustBeMember(IncludedEdge,["left","right"])} = "left"
end
this.BinEdges = BinEdges;
this.Value = Value;
this.IncludedEdge = IncludedEdge;
this.update();
end
function update(this)
try % lazy way to only do when all data are set
V = this.Value(:);
S = size(this.Value);
BIDs = discretize(V,this.BinEdges,"IncludedEdge",this.IncludedEdge);
this.BinIDs = reshape(BIDs,S);
this.LeftEdges = reshape(this.BinEdges(BIDs ),S);
this.RightEdges = reshape(this.BinEdges(BIDs+1),S);
end
end
function set.BinEdges(this,val)
this.BinEdges = val;
this.update();
end
function set.Value(this,val)
this.Value = val;
this.update();
end
function set.IncludedEdge(this,val)
this.IncludedEdge = val;
this.update();
end
end
methods (Access = protected)
function displayScalarObject(this)
switch this.IncludedEdge
case "left"
lb = "[";
rb = ")";
case "right"
lb = "(";
rb = "]";
end
disp(...
compose("%s%d,%d%s",lb,this.LeftEdges,this.RightEdges,rb) ...
);
end
end
end
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!