Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 39 additions & 29 deletions inst/tabulate.m
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,11 @@
endif

total = sum (counts);
percents = 100 * counts ./ total;
if (total == 0)
percents = zeros (size (counts));
else
percents = 100 * counts ./ total;
endif

## Output format: Cell array
out = cell (length (vals), 3);
Expand All @@ -96,40 +100,21 @@
## Handle string arrays
x(ismissing (x)) = [];

## Convert to cellstr and use grp2idx which is robust
[idx, vals] = grp2idx (cellstr (x));

if (isempty (idx))
counts = [];
percents = [];
if (isempty (x))
out = cell (0, 3);
else
counts = accumarray (idx, 1);
total = sum (counts);
percents = 100 * counts ./ total;
endif
## Convert to cellstr and use grp2idx which is robust
[idx, vals] = grp2idx (cellstr (x));

## Output format: Cell array
vals_cell = vals;
out = cell (length (vals_cell), 3);
out(:,1) = vals_cell;
out(:,2) = num2cell (counts);
out(:,3) = num2cell (percents);

if (isempty (idx))
counts = [];
percents = [];
else
counts = accumarray (idx, 1);
total = sum (counts);
percents = 100 * counts ./ total;
endif

## Output format: Cell array
vals_cell = vals;
out = cell (length (vals_cell), 3);
out(:,1) = vals_cell;
out(:,2) = num2cell (counts);
out(:,3) = num2cell (percents);
out = cell (length (vals), 3);
out(:,1) = vals;
out(:,2) = num2cell (counts);
out(:,3) = num2cell (percents);
endif

elseif (islogical (x))
## Handle logical arrays
Expand Down Expand Up @@ -407,3 +392,28 @@
%!error<tabulate: X must be either a numeric vector> tabulate ({1, 2, 3, 4})
%!error<tabulate: X must be either a numeric vector> ...
%! tabulate ({"a", "b"; "a", "c"})

## Test categorical with all undefined values (should return zero counts/percents)
%!test
%! x = categorical ({'a','b','c'});
%! x(:) = categorical (missing);
%! tbl = tabulate (x);
%! assert (iscell (tbl));
%! assert ([tbl{:,2}]', [0; 0; 0]);
%! assert ([tbl{:,3}]', [0; 0; 0]);

## Test categorical with defined categories but no data
%!test
%! x = categorical ({}, {'low','med','high'});
%! tbl = tabulate (x);
%! assert (iscell (tbl));
%! assert ([tbl{:,2}]', [0; 0; 0]);
%! assert ([tbl{:,3}]', [0; 0; 0]);

## Test string array with all missing values (should return empty table)
%!test
%! x = string ({'a','b'});
%! x(:) = missing;
%! tbl = tabulate (x);
%! assert (iscell (tbl));
%! assert (isempty (tbl));