How to count the number of non-nan values for combination of multiple variables

2 ビュー (過去 30 日間)
Blue
Blue 2024 年 7 月 17 日
コメント済み: Blue 2024 年 7 月 17 日
Hello, I would like to count the number of non-nan values in the d column for unique combinations of a, b and c (i.e I want to generate the e column in tt). If any a,b or c are NaN then the count should be nan as well
% Initial table
a = [1,1,1,2,2,2,2]';
b = [660, 661, 661, 663, 663, NaN, 663]';
c = [1,2,2,5,5,NaN,6]';
d = [11,12,NaN, 13, 14, NaN,5]';
t = table(a,b,c,d)
t = 7x4 table
a b c d _ ___ ___ ___ 1 660 1 11 1 661 2 12 1 661 2 NaN 2 663 5 13 2 663 5 14 2 NaN NaN NaN 2 663 6 5
% Desired output
a = [1,1,1,2,2,2,2]';
b = [660, 661, 661, 663, 663, NaN, 663]';
c = [1,2,2,5,5,NaN,6]';
d = [11,12,NaN, 13, 14, NaN,5]';
e = [1, 1, 1, 2, 2, NaN, 1]';
tt = table(a,b,c,d,e)
tt = 7x5 table
a b c d e _ ___ ___ ___ ___ 1 660 1 11 1 1 661 2 12 1 1 661 2 NaN 1 2 663 5 13 2 2 663 5 14 2 2 NaN NaN NaN NaN 2 663 6 5 1

採用された回答

Voss
Voss 2024 年 7 月 17 日
編集済み: Voss 2024 年 7 月 17 日
% Initial table
a = [1;1;1;2;2;2;2];
b = [660; 661; 661; 663; 663; NaN; 663];
c = [1;2;2;5;5;NaN;6];
d = [11;12;NaN; 13; 14; NaN;5];
t = table(a,b,c,d)
t = 7x4 table
a b c d _ ___ ___ ___ 1 660 1 11 1 661 2 12 1 661 2 NaN 2 663 5 13 2 663 5 14 2 NaN NaN NaN 2 663 6 5
G = {'a','b','c'};
F = @(x)nnz(~isnan(x));
T = groupsummary(t,G,F,'d');
[~,~,idx] = unique(t(:,G),'rows');
e = T.fun1_d(idx);
e(any(isnan(t{:,G}),2)) = NaN;
tt = addvars(t,e)
tt = 7x5 table
a b c d e _ ___ ___ ___ ___ 1 660 1 11 1 1 661 2 12 1 1 661 2 NaN 1 2 663 5 13 2 2 663 5 14 2 2 NaN NaN NaN NaN 2 663 6 5 1

その他の回答 (1 件)

J. Alex Lee
J. Alex Lee 2024 年 7 月 17 日
編集済み: J. Alex Lee 2024 年 7 月 17 日
Not sure what d and e need to be, but i think this should at least partially help
a = [1,1,1,2,2,2,2]';
b = [660, 661, 661, 663, 663, NaN, 663]';
c = [1,2,2,5,5,NaN,6]';
x = [a,b,c]
x = 7x3
1 660 1 1 661 2 1 661 2 2 663 5 2 663 5 2 NaN NaN 2 663 6
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
% any(_,2) goes row-wise ORs.
any(isnan(x),2)
ans = 7x1 logical array
0 0 0 0 0 1 0

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

タグ

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by