If you want to create a new table with two new variables, one for the number of unique countries and one for the list of unique countries then a) you have to use rowfun instead of varfun, and b) you can't use an anonymous function (since you need a function with 2 outputs) but a normal m function:
function [count, list] = uniquecountries(countries)
validateattributes(countries, {'categorical'}, {});
list = unique(countries);
count = numel(list);
list = {strjoin(cellstr(list), ', ')};
end
Then:
sections = rowfun(@uniquecountries, fullTable, ...
'GroupingVariables', {'ID1','Date'}, ...
'InputVariables', 'Country', ...
'NumOutputs', 2, ...
'OutputVariableNames', {'Country_count', 'Country_list'})
Alternatively, if you don't want a separate m function, you can have two calls to rowfun or varfun to create two tables that you then join. It will be much slower however:
sectionscount = rowfun(@(v) numel(unique(v)), fullTable, ...
'GroupingVariables', {'ID1','Date'}, ...
'InputVariables', 'Country', ...
'OutputVariableNames', 'Country_count');
sectionslist = rowfun(@(v) {strjoin(cellstr(unique(v)), ', ')}, fullTable, ...
'GroupingVariables', {'ID1','Date'}, ...
'InputVariables', 'Country', ...
'OutputVariableNames', 'Country_list');
sections = join(sectionscount, sectionslist)
Best Answer