How to count the number of rows per group

7 visualizaciones (últimos 30 días)
Blue
Blue el 29 de Sept. de 2022
Respondida: David Hill el 29 de Sept. de 2022
Hi, I simply want to count the number of rows per group (for unique combinations of a, b and c). Groups where either a, b, or c are NaN should have a number of rows of NaN in the desired_output table.
% Original table
a = [1, 1, 1, 1, 2, 3, 3, 3]';
b = [NaN, NaN, NaN, NaN, 10, 23, 23, 23]';
c = [NaN, NaN, NaN, NaN, 5, 6, 6, 6]';
T = table(a, b, c)
T = 8×3 table
a b c _ ___ ___ 1 NaN NaN 1 NaN NaN 1 NaN NaN 1 NaN NaN 2 10 5 3 23 6 3 23 6 3 23 6
% desired_output
a = [1, 1, 1, 1, 2, 3, 3, 3]';
b = [NaN, NaN, NaN, NaN, 10, 23, 23, 23]';
c = [NaN, NaN, NaN, NaN, 5, 6, 6, 6]';
d = [NaN, NaN, NaN, NaN, 1, 3, 3, 3]';
desired_output = table(a, b, c, d)
desired_output = 8×4 table
a b c d _ ___ ___ ___ 1 NaN NaN NaN 1 NaN NaN NaN 1 NaN NaN NaN 1 NaN NaN NaN 2 10 5 1 3 23 6 3 3 23 6 3 3 23 6 3
Thank you,
  4 comentarios
Image Analyst
Image Analyst el 29 de Sept. de 2022
I tried some ways using table2array and unique but none of them was a one-liner. If you have a few lines of code that does it, just go with that. Sometimes longer code is better because it's more readable and understandable rather than a cryptic one-liner that no one can understand.
Blue
Blue el 29 de Sept. de 2022
% Here is what I would attempt to go from T to desired output but Im stuck at the last row and anyhow this feels clumsy.
% Calculate number of rows per group
g = groupcounts(T, {'a', 'b', 'c'}, IncludeMissingGroups = false);
g.Percent = [];
g = renamevars(g, 'GroupCount', 'n_rows');
% Find unique combinations
[idx, idy] = ismember(T(:, {'a', 'b', 'c'}), g(:, {'a', 'b', 'c'}), 'rows');
% Assign back to T. Stuck here
% T = g(idy(idx), 4)];

Iniciar sesión para comentar.

Respuesta aceptada

David Hill
David Hill el 29 de Sept. de 2022
A=[a,b,c];
u=unique(A,'rows');
d=zeros(size(A,1),1);
idx=any(isnan(A),2);
d(idx)=nan;
f=find(~idx);
for k=1:length(f)
d(f(k))=sum(ismember(A,A(f(k),:),'rows'));
end

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by