MATLAB Answers


Can we categorize and sum 2 columns from table

Asked by Varad More on 24 Jun 2019 at 19:21
Latest activity Commented on by Varad More on 26 Jun 2019 at 17:50
Here I've a table data temp with disease names & date as columns. How can I find sum/count of a particular disease on a given day. Was able to calculate individually:
%%for disease
data_temp.Disease = categorical (data_temp.Disease);
m_val = unique (data_temp.Disease );
m=arrayfun(@(x) sum(data_temp.Disease==x),m_val);
%% categorising &counting Date
data_temp.Date = categorical (data_temp.Timestamps);
date = unique (data_temp.Date);
m=arrayfun(@(x) sum(data_temp.Date==x),date);
How can we use both parameters together?


Sign in to comment.

1 Answer

Answer by Guillaume
on 24 Jun 2019 at 20:28
 Accepted Answer

There are plenty of functions to compute aggregrate properties of table. groupsummary is one way, split-apply-combine workflow is another, rowfun another one.
If I understood correctly:
rowfun(@nnz, data_temp, 'GroupingVariables', {'Timestamps', 'Disease'}, 'InputVariables', 'Timestamps');
groupsummary(data_temp, {'Timestamps', 'Disease'}, 'nnz', 'Timestamps');
Note that if Disease is not categorical already you should make it categorical once and for all in your table:
data_temp = convertvars(data_temp, 'Disease', 'categorical');
Timestamps on the other should be of type datetime, not a categorical array.

  1 Comment

Thanks a lot. That's what I was searching for.

Sign in to comment.