How can I merge rows into one with the same ID number?

3 views (last 30 days)
I have a spreadsheet with patient IDs and diagnoses; all diagnoses are in their own column and I want to merge the rows based on patient ID to make one row and keep all the data. I'm not sure how to go about doing this?
Example of table:
PT Dx1 Dx2 Dx3
A 1 0 0
A 0 1 0
A 0 0 1
I want:
PT Dx1 Dx2 Dx3
A 1 1 1

Answers (1)

Stephen23
Stephen23 on 21 Sep 2020
Edited: Stephen23 on 22 Sep 2020
Assuming that the non-diagonal values are exactly zero, then you could use varfun something like this:
>> T = cell2table({'A',1,0,0;'A',0,2,0;'A',0,0,3;'B',4,0,0;'B',0,5,0;'B',0,0,6})
T =
Var1 Var2 Var3 Var4
____ ____ ____ ____
'A' 1 0 0
'A' 0 2 0
'A' 0 0 3
'B' 4 0 0
'B' 0 5 0
'B' 0 0 6
>> U = varfun(@sum,T,'GroupingVariables','Var1')
U =
Var1 GroupCount sum_Var2 sum_Var3 sum_Var4
____ __________ ________ ________ ________
A 'A' 3 1 2 3
B 'B' 3 4 5 6
Of course you can rename/remove those table variables as required.

Categories

Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!